Toni Michel Caubet
Toni Michel Caubet

Reputation: 20163

.replace(' ', '-') will only replace first whitespace

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.net/7ycg3/

Upvotes: 2

Views: 7308

Answers (5)

Vishal Suthar
Vishal Suthar

Reputation: 17194

Use /\s/g inplace of ' ' in your question

Upvotes: 0

Chris Morgan
Chris Morgan

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, include g 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

jAndy
jAndy

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

Jon
Jon

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

Andreas Wong
Andreas Wong

Reputation: 60516

http://jsfiddle.net/7ycg3/1/

Use regex with /g modifier

Upvotes: 0

Related Questions