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,279
  • 5
  • 35
  • 57
strudelkopf
  • 671
  • 1
  • 6
  • 12

3 Answers3

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?

Community
  • 1
  • 1
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
  • Replace all: http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript – Fabio Filippi May 02 '14 at 07:08
  • 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 May 02 '14 at 07:15
  • @T.J.Crowder - Your'e right about that, I've searched for a fix and edited my post. – Amir Popovich May 02 '14 at 07:51
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/

suneetha
  • 827
  • 1
  • 6
  • 14
0

Try this:

var str = "ID: :ID:";
str = str.replace(/:ID:/gi, "0");
console.log(str);
Aidal
  • 799
  • 4
  • 8
  • 33