Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all instances in string with a variable as the search - JavaScript

I am having an issue which I cannot find documented anywhere, i see a regex method however that is using a direct string rather than string within 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 gets a url variable (srcStr) and searches a body of text within .entry-content for the string stored in the var src.

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

Is there a solution?

like image 341
Josh Boothe Avatar asked Jan 14 '23 20:01

Josh Boothe


1 Answers

You are searching for the pattern that is literally "src." You need to use the RegExp class if you want to use variables in patterns:

pattern = new RegExp(src, 'g');
$(".entry-content")...html().replace(pattern, replacement);
like image 163
Explosion Pills Avatar answered Jan 17 '23 16:01

Explosion Pills