0

I have the following string

var str = "this---is--- a --- test d ---";

I want to remove all the - and replace by nothing.

I tried using

var str = "this---is--- a --- test d ---";
var res = str.replace("-", "");

but res do not change...

if I do

var str = "this---is--- a --- test d ---";
var res = str.split('-').filter(e => !!e).join();

it does work.

Why the replace is not ?

Bobby
  • 4,372
  • 8
  • 47
  • 103

1 Answers1

4

Because replace will only replace one occurrence.

"aabc".replace("a", ""); // Outputs "abc"
"aabc".replaceAll("a", ""); // Outputs "bc"

Use replaceAll to replace all occurrences

var str = "this---is--- a --- test d ---";
var res = str.replaceAll("-", "");
Constantin
  • 848
  • 8
  • 23