[Solved] Extract Parenthesis Task in HTML with DOM and JavaScript

  

3
Topic starter

Write a JS function that when executed, extracts all parenthesized text from a target paragraph by given element ID. The result is a string, joined by "; " (semicolon, space).

Input:
Your function will receive a string parameter, representing the target element ID, from which text must be extracted. The text should be extracted from the DOM.

Output:
Return a string with all matched text, separated by "; " (semicolon, space).

Examples:

extract parenthesis javascript task

1 Answer
2

Here is my solution:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<p id="content">
    Rakiya (Bulgarian brandy) is home-made liquor (alcoholic drink). It can be made of grapes, plums or other fruits
    (even apples).
</p>
 
<p id="holder">
    Lorem ipsum dolor sit amet, (consectetur adipiscing elit), sed do eiusmod (tempor) incididunt ut labore (et dolore
    magna) aliqua.
</p>
 
<script>
 function extract(elementId){
     let para = document.getElementById(elementId).textContent;
     let pattern=/\(([^)]+)\)/g;
     let result = [];
 
     let match = pattern.exec(para);
     while(match){
         result.push(match[1]);
         match=pattern.exec(para);
     }
     return result.join("; ")
 }
</script>
 
</body>
</html>
Share: