0

I can't figure out why this code isn't working.

I want to replace a placeholder with an actual value. Sample code as below:

var str = "ID: :ID:";
str.replace(":ID:", 0);
console.log(str);

Output:

ID: :ID:

This is my JSFiddle

2

3 Answers 3

4

The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

var str = "ID: :ID:";
str = str.replace(":ID:", 0);
console.log(str);

replace

P.s. replace only replaces the first occurrence.
Use replace all if you want to replace all occurrences:
How to replace all occurrences of a string in JavaScript?

Sign up to request clarification or add additional context in comments.

3 Comments

If you pass find raw into the RegExp constructor, the various regex special characters will cause trouble. For instance, if find is "Mr. Smith" you'll replace "Mrs Smith" as well.
@T.J.Crowder - Your'e right about that, I've searched for a fix and edited my post.
0

Your just replacing the string, but not storing it back. So, it is giving previous string rather than new one.

var str = "ID: :ID:";
str = str.replace(":ID:", 0);
console.log(str);

JS Fiddle: http://jsfiddle.net/B9n79/2/

2 Comments

Note that this will only replace the first occurrence of :ID:.
Yes. we can use regular expressions to replace all occurrences
0

Try this:

var str = "ID: :ID:";
str = str.replace(/:ID:/gi, "0");
console.log(str);

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.