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?
/
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?
http://jsfiddle/7ycg3/
Share Improve this question asked Mar 26, 2012 at 10:41 Toni Michel CaubetToni Michel Caubet 20.2k58 gold badges217 silver badges387 bronze badges5 Answers
Reset to default 6You 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.
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
.
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,'-')
.
http://jsfiddle/7ycg3/1/
Use regex with /g
modifier
Use /\s/g
inplace of ' '
in your question