将字符串中的所有实例替换为搜索- JavaScript。

时间:2022-01-17 16:49:10

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:

我遇到了一个问题,我在任何地方都找不到文档,我看到了一个regex方法,但是它使用的是一个直接字符串,而不是变量中的字符串。这是我的代码:

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.

这将获取一个url变量(srcStr),并在.entry-content中搜索存储在var src中的字符串。

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

问题代码在这里:replace(/src/g)

Is there a solution?

有解决方案吗?

1 个解决方案

#1


9  

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:

您正在搜索的模式字面上是“src”。如果您想在模式中使用变量,需要使用RegExp类:

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

#1


9  

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:

您正在搜索的模式字面上是“src”。如果您想在模式中使用变量,需要使用RegExp类:

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