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?

4 Answers 4

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

1 Comment

+1 mate. Some of us just answered the question. You thought about the best way of doing it.
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);

Comments

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);

Comments

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");

Comments

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.