Skip to content
Advertisement

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?

Advertisement

Answer

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}\)`);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement