简体   繁体   English

将变量中的所有实例替换为变量作为搜索 - JavaScript

[英]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 . 这将获取一个url变量(srcStr),并在.entry-content中搜索文本正文,以查找var src存储的字符串。

The problem code is here: replace(/src/g 问题代码在这里: replace(/src/g

Is there a solution? 有解决方案吗?

You are searching for the pattern that is literally "src." 您正在搜索字面上为“src”的模式。 You need to use the RegExp class if you want to use variables in patterns: 如果要在模式中使用变量,则需要使用RegExp类:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM