JavaScript replace match - how to use variable in regex pattern ?

How should I use a JavaScript variable in regex pattern to match value that I need to replace ?
0
give a positive ratinggive a negative rating
12 Dec 2022 at 06:36 PM
Hi,

To get the match using a Javascript variable in regex pattern, you have to use replace(), but also a RegExp object. For example:

<script>

function replaceItem(content, variable) {
var r = new RegExp("\\s" + variable , "i");
var v = content.replace(r, " <a href='https://www.example.com' target='_blank' >"+variable+"</a>");
return v;
}

var c = replaceItem('Please click on this link', 'link');
alert(c);

</script>

0
give a positive ratinggive a negative rating
13 Dec 2022 at 09:53 AM
Tim
Share on FacebookShare on TwitterShare on LinkedInSend email
x
x
2024 AnswerTabsTermsContact us