0

I can't replace the substring in a string:

var source = "div.col-md-4.fields:visible:eq(0) div.panel-body select:eq(0)";
var modified = source.replace(/visible:eq(0)/g, "1234");

I wonder why does modified have the same value as source?

Incerteza
  • 32,326
  • 47
  • 154
  • 261

4 Answers4

4

You should not use regular expressions here but a simple string replace function. It will run faster and regular expressions were not made for simple tasks like this as they will run slightly slower than the simple replace function. Using regular expressions here is like using a nuke to open a water bottle, rather prefer simplicity, if a developer sees this code he will like the simplicity.

Change your second line to this one:

var modified = source.replace("visible:eq(0)", "1234");
Valentin Mercier
  • 5,256
  • 3
  • 26
  • 50
  • +1 mate. Some of us just answered the question. You thought about the best way of doing it. – Harry Jul 19 '14 at 10:58
1

You need to escape the brackets

    var source = "div.col-md-4.fields:visible:eq(0) div.panel-body select:eq(0)";
    var modified = source.replace(/visible:eq\(0\)/g, "1234");

    console.log(source);
    console.log(modified);
name not found
  • 622
  • 4
  • 13
0

You just need to escape your chars like this Demo: http://jsfiddle.net/cvW24/1/

hope rest help the cause :)

if you keen:

code

var source = "div.col-md-4.fields:visible:eq(0) div.panel-body select:eq(0)";
var modified = source.replace(/visible:eq\(0\)/g, "1234");

alert(modified);
Community
  • 1
  • 1
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
0

Because your regular expression does not match the string. You need to escape the parenthesis.

var modified = source.replace(/visible:eq\(0\)/g, "1234");
max
  • 96,212
  • 14
  • 104
  • 165