0

I got following code snippet, it's pretty simple,


var b = "'aa','bb'";

console.log(b.replace("'", ""));
// result is "aa','bb'"

I want replace all single quote signs with blank. So my expected output should be "aa,bb", but the actual output is "aa','bb'" neither run this code snippet in Node nor browser. Seems only the first single quote sign has been replaced. I already got a workaround to resolve this problem by replace with regex. What I wanna know is what happened to replace function here? I cannot figure this out.

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Kevin Law
  • 814
  • 4
  • 15
  • I found the answer from MDN, this is the JavaScript default behavior, which is different from most languages I know. – Kevin Law Mar 11 '20 at 02:13

1 Answers1

1

Try using RegEx specifying the global flag (g) that matches the pattern multiple times. Please also note that, as replace() does not modify the original string you have to reassign the modified value to the variable:

var b = "'aa','bb'";
b = b.replace(/'/g, "");
console.log(b);
Mamun
  • 66,969
  • 9
  • 47
  • 59