Replace all instances in a variable string as search - JavaScript

I am having a problem that I cannot find anywhere documented, I see a regular expression method, but I use a straight line, not a line inside a variable. This is my code:

var src = getQueryVariable("srcStr"); if(src != false){ $(".entry-content").html($(".entry-content") .html().replace(/src/g, "<span style='background-color:#f2e128;'>" + src + "</span>")); } 

This takes the url variable (srcStr) and looks for text text inside the .entry content for the string stored in var src .

The problem code is here: replace(/src/g

Is there a solution?

+4
source share
1 answer

You are looking for a template that is literally "src". You need to use the RegExp class if you want to use variables in templates:

 pattern = new RegExp(src, 'g'); $(".entry-content")...html().replace(pattern, replacement); 
+9
source

All Articles