Reputation: 23
I am trying to format a string into word+word+word
For example
"ultra music festival" into "ultra+music+festival"
I have tried using following codes
query.split(" ").join("+");
or
query.replace(" ", "+");
however, both ways will give me
"ultra+music festival"
what is causing this issue, and how can i fix it ?
Upvotes: 0
Views: 52
Reputation: 36438
The first version (split
/join
) should work as-is (if the second space is really a space).
To replace more than one space using replace()
, you'll need the g
flag:
query.replace(/ /g, "+");
To replace multiple spaces (or tabs, or other whitespace) in a row, you'd use:
query.replace(/\s+/g, "+");
so that "one two three"
would still turn into "one+two+three"
.
Upvotes: 1
Reputation: 40
the global attribute is important.
Example!
var str = "Mr Blue has a blue house and a blue car";
var res = str.replace(/blue/g, "red");
in this case:
query.replace(/ /g, "+");
Upvotes: 0