10

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
  • Do you need to use a regular expression? If so, be aware that if old_string contained any meaningful regular expression characters such as (, ), *, ., -, etc will need to be escaped or will probably break your replace. Commented Jan 23, 2012 at 16:24

4 Answers 4

22

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"));
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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')})

Comments

0

Create a RegExp object:

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

Edit: Fixed parameters

1 Comment

the constructor for RegExp does not need the leading and trailing / and the g should be the second argument. Javascript RegExp Object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.