9

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
  • 22,682
  • 52
  • 149
  • 235
  • 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

21

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
  • 67,648
  • 11
  • 84
  • 121
1

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
  • 118,012
  • 12
  • 125
  • 175
0

Create a RegExp object:

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

Edit: Fixed parameters

Yogu
  • 8,033
  • 4
  • 31
  • 51
  • 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
  • 20,786
  • 4
  • 51
  • 70