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

Bhushan Kawadkar
28.6k5 gold badges39 silver badges61 bronze badges
asked May 2, 2014 at 7:05
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?

answered May 2, 2014 at 7:06
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/

answered May 2, 2014 at 7:13

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);
answered May 2, 2014 at 8:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.