The intention of the regex is to capture substrings wrapped between twin expressions in parentheses, kinda like html tags. For example:
JavaScript
x
2
1
<p id="textTwo">And this shall be (blue)the ocean(blue) and this shall also be like (blue)the ocean(blue)</p>
2
And here’s my code
JavaScript
1
5
1
let color = 'blue';
2
let getColor =
3
new RegExp(`(${color})(.*)(${color})`);
4
let coloredText = textTwo.match(getColor);
5
JavaScript
1
19
19
1
let text = document.getElementById('text').innerText;
2
let textTwo = document.getElementById('text2').innerText;
3
4
let color = 'blue';
5
let getColor =
6
new RegExp(`(${color})(.*)(${color})`);
7
let coloredText = textTwo.match(getColor);
8
// italicsText.forEach((string, index) => {
9
// string.replace("(i)", "<i>");
10
// console.log(typeof(string));
11
// });
12
// text.replace(italics, "<i>");
13
14
let italics = text.replace(/((.*?))/g, (_, match) => `<${match}>`);
15
console.log(italics);
16
17
18
console.log(italics);
19
console.log(coloredText);
JavaScript
1
3
1
<p id="text">Hello there (i)Good Sir(i). How can I help you (i)today(i)</p>
2
3
<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
:
JavaScript
1
4
1
let color = 'blue';
2
let getColor =
3
new RegExp(`\(${color}\)(.*)\(${color}\)`);
4