Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex expression not returning entire term

The intention of the regex is to capture substrings wrapped between twin expressions in parentheses, kinda like html tags. For example:

<p id="textTwo">And this shall be (blue)the ocean(blue) and this shall also be like (blue)the ocean(blue)</p>

And here’s my code

let color = 'blue';
let getColor = 
    new RegExp(`(${color})(.*)(${color})`);
let coloredText = textTwo.match(getColor);
let text = document.getElementById('text').innerText;
let textTwo = document.getElementById('text2').innerText;

let color = 'blue';
let getColor = 
    new RegExp(`(${color})(.*)(${color})`);
let coloredText = textTwo.match(getColor);
// italicsText.forEach((string, index) => {
//   string.replace("(i)", "<i>");
//   console.log(typeof(string));
// });
// text.replace(italics, "<i>");

let italics = text.replace(/\((.*?)\)/g, (_, match) => `<${match}>`);
console.log(italics);


console.log(italics);
console.log(coloredText);
<p id="text">Hello there (i)Good Sir(i). How can I help you (i)today(i)</p>

<p id="text2">And this shall be (blue)ao!(blue) and this shall also be (blue)like the ocean(blue)</p>

Can anyone tell me why this doesn’t capture the entire thing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The characters () are special in a regexp and must be escaped with a \ if you want to match them literally. And because \ in a JavaScript string literal is also special, it needs to be escaped with another \:

    let color = 'blue';
    let getColor = 
        new RegExp(`\\(${color}\\)(.*)\\(${color}\\)`);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading