Reputation: 20163
i am trying
To convert: 'any string separated with blankspaces'
into
'any-string-separated-with-blankspaces'
i am tying with .replace(' ','-')
but it would only replace first... why? how can i replace all?
Upvotes: 2
Views: 7308
Reputation: 90742
It's not stated particularly clearly in the MDN docs for String.replace
, but String.replace
only does one replacement, unless the g
flag is included in it, using a regular expression rather than a string:
To perform a global search and replace, either include the
g
switch in the regular expression or if the first parameter is a string, includeg
in the flags parameter.
(But be aware that the flags
parameter is non-standard, as they also note there.)
Thus, you want tag.replace(/ /g,'-')
.
Upvotes: 1
Reputation: 235992
You need a regular expression for that
.replace(/\s/g,'-')
\s
will replace any kind of white-space character. If you're strictly after a "normal" whitespace use
/ /g
instead.
Upvotes: 6
Reputation: 437366
You need to use a regular expression as the first parameter, using the /g
modifier to make it replace all occurrences:
var replaced = input.replace(/ /g,'-');
If you want to replace any whitespace character instead of a literal space, you need to use \s
instead of in the regex; and if you want to replace any number of consecutive spaces with one hyphen, then add
+
after the or
\s
.
Upvotes: 1