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?

Shpigford
  • 24,748
  • 58
  • 163
  • 252
  • 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. – Sam Greenhalgh Jan 23 '12 at 16:24

4 Answers4

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"));
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
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

Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

Create a RegExp object:

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

Edit: Fixed parameters

Yogu
  • 9,165
  • 5
  • 37
  • 58
  • the constructor for RegExp does not need the leading and trailing `/` and the `g` should be the second argument. [Javascript RegExp Object](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp) – Sam Greenhalgh Jan 23 '12 at 16:29
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')})
bjornd
  • 22,397
  • 4
  • 57
  • 73