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
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>

Share on FacebookShare on TwitterShare on LinkedInSend email
1 answer
x
x
2024 AnswerTabsTermsContact us