将字符串中的所有实例替换为搜索的变量 - JavaScript [英] Replace all instances in string with a variable as the search - JavaScript

查看:71
本文介绍了将字符串中的所有实例替换为搜索的变量 - JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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




$ p $获得一个url变量(srcStr)并搜索一个body存储在var src 中的字符串.entry-content中的文本。



问题代码如下: replace(/ src / g



是否有解决方案?

解决方案

您正在寻找字面意义上为src的模式。如果您需要,您需要使用 RegExp 类在模式中使用变量:

  pattern = new RegExp(src,'g'); 
$(。 ();


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?

解决方案

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

这篇关于将字符串中的所有实例替换为搜索的变量 - JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆