-6
text = "1/2/3"
result = text.replace("/", "");

I expect the result to be "123" but instead it's "12/3" Why?

Demian Kasier
  • 2,475
  • 6
  • 30
  • 40
  • 1
    This is a good answer: [Replacing all occurrences of a string in JavaScript](http://stackoverflow.com/a/1144788/3088045) – Kamafeather Aug 28 '14 at 11:23
  • possible duplicate of [Why does javascript replace only first instance when using replace?](http://stackoverflow.com/questions/1967119/why-does-javascript-replace-only-first-instance-when-using-replace) – Wooble Aug 28 '14 at 11:26
  • @Kamafeather Thx, just looked at it, and it's exactly what I needed – Demian Kasier Aug 28 '14 at 11:29
  • Voted to close my own question, since it is, indeed, a duplicate – Demian Kasier Aug 29 '14 at 05:56

5 Answers5

5

Add the global selection "g" flag and use a regex instead of a string in first parameter.

result = text.replace(/\//g, "");
Ahmad
  • 1,913
  • 13
  • 21
1

You can do this with regular expression as argument to replace with global selection.

"1/2/3".replace(/\//g, "")
Vishwanath
  • 6,284
  • 4
  • 38
  • 57
0

You can try the below Regexp

"1/2/3".replace(/\//g,"");

This will replace all the / elements with "".

0

Another way of doing the same:

String.prototype.replaceAll = function(matchStr, replaceStr) {
  return this.replace(new RegExp(matchStr, 'g'), replaceStr);
 };
var str = "1/2/3";
result = str.replaceAll('/', '');
Tapaswi Panda
  • 1,041
  • 7
  • 13
-1
a = "1/2/3"
a =a.split("/").join("")
NIlesh Sharma
  • 5,445
  • 6
  • 36
  • 53