jQuery replace with variable?

2020-07-08 06:56发布

问题:

I'm trying to do a replace on a string like this:

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

But the abc123 actually needs to be a variable.

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?

回答1:

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

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


回答2:

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

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

Some useful info here



回答3:

You can create regular expression using constructor.

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

Here is RegExp documentation.

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

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


回答4:

Create a RegExp object:

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

Edit: Fixed parameters