jQuery 替换为变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8974784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:20:57  来源:igfitidea点击:

jQuery replace with variable?

jqueryreplace

提问by Shpigford

I'm trying to do a replaceon a string like this:

我正在尝试对这样replace的字符串执行操作:

$('#example_id').replace(/abc123/g,'something else')

But the abc123actually needs to be a variable.

abc123实际上需要是一个变量。

So something like:

所以像:

var old_string = 'abc123'
$('#example_id').replace(/old_string/g,'something else')

So how would I use a variable in the replace function?

那么如何在替换函数中使用变量呢?

回答by ShankarSangoli

First of $('#example_id')will give you a jQuery object, you must be replacing string inside its html or value. Try this.

首先$('#example_id')会给你一个 jQuery 对象,你必须在它的 html 或值中替换字符串。尝试这个。

var re = new RegExp("abc123","g");
$('#example_id').html($('#example_id').html().replace(re, "something else"));

回答by Jamiec

There is another version of replace which takes a RegExpobject. This object can be built up from a string literal:

还有另一个版本的 replace 需要一个RegExp对象。这个对象可以从字符串文字构建:

var old_string = "abc123";
var myregexp = new RegExp(old_string,'g');
$('#example_id').replace(myregexp,'something else')

Some useful info here

一些有用的信息在这里

回答by Yogu

Create a RegExpobject:

创建一个RegExp对象:

var regexp = new RegExp(old_string, 'g');
$('#example_id').replace(regexp,'something else');

Edit:Fixed parameters

编辑:固定参数

回答by bjornd

You can create regular expression using constructor.

您可以使用构造函数创建正则表达式。

var re = new RegExp('abc123', 'g')
$('#example_id').replace(re,'something else')

Here is RegExpdocumentation.

这是RegExp文档。

For replacing element's inner html content you can use html method:

要替换元素的内部 html 内容,您可以使用 html 方法:

$('#example_id').html(function(i, s){return s.replace(re, 'replace with')})