-1

When I run this in my console:

var test = "A-Test (One Two 3)"
test.toLowerCase().replace(" ", "").replace("-", "");

The output is:

atest(one two 3)

Why aren't the spaces inside the parenthesis being replaced?

How can I strip all spaces?

Nate
  • 26,164
  • 34
  • 130
  • 214

1 Answers1

3

To replace mulitple instances of a pattern, with String.replace() you have to use a regular expression, rather than a string, to identify the specific instance(s) to be replaced, along with the g modifier:

var test = "A-Test (One Two 3)"
test.toLowerCase().replace(/ /g, "").replace("-", "");

var test = "A-Test (One Two 3)",
  modifiedTest = test.toLowerCase().replace(/ /g, "").replace("-", "");

console.log(modifiedTest);
David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • So `.replace()` only replaces the first occurrence? That's really counter intuitive.. If I want to replace an unlimited number of spaces and dashes, then, I should change your code to the following? `test.toLowerCase().replace(/ -/g, "");` – Nate Sep 28 '14 at 22:17
  • 1
    @Nate `test.toLowerCase().replace(/[ -]/g, "");` – Tom Sep 28 '14 at 22:18
  • That depends, the way you have it written there it'll replace any sequence of space-hyphen (`' -'`) with a zero-space string, *not* space *or* hyphen. – David Thomas Sep 28 '14 at 22:19
  • @Nate: These sorts of questions have been asked hundreds of times. Please take the time to search. –  Sep 28 '14 at 22:19
  • @squint: to be fair, I should've done that myself. Thanks! :) – David Thomas Sep 28 '14 at 22:19
  • @squint I did search. I also looked at the related questions. – Nate Sep 28 '14 at 22:19
  • @Nate: You did? The related questions provide answers. So what's the problem? –  Sep 28 '14 at 22:22
  • @squint Before I submitted my question I looked at the first few related questions. Maybe they changed after I submitted, or maybe I didn't read all of them.. In any case, I don't see duplicate questions like this as a bad thing, because next time someone searches for `Spaces not being replaced with .replace()?` this will come up and they'll have an answer. – Nate Sep 28 '14 at 22:24
  • @Nate: Typing javascript + that phrase into Google, they would have come up with several answers even if you hadn't posted this question. Please take the time to search. –  Sep 28 '14 at 22:26