最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - .replace(' ', '-') will only replace first whitespace - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

5 Answers 5

Reset to default 6

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.

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, 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,'-').

http://jsfiddle/7ycg3/1/

Use regex with /g modifier

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

发布评论

评论列表(0)

  1. 暂无评论