开发者

How to prevent this regex that replaces hyphens with spaces from also replacing hyphens with additional hyphens?

This regex:

str.replace(/ +/g, '-').toLowerCase();

will convert this:

The dog jumped over the lazy - chair

into this:

the-dog-jumped-over-the-lazy---chair

How to modify it so it produces this instead (only a single hyphen):

the-dog-jumped-over-t开发者_开发知识库he-lazy-chair


I would assume your actual input is "The dog jumped over the lazy - chair", with spaces around that hyphen getting converted, since there's no other reason the pattern should match there.

Try this:

str.replace(/( +- *)|(- +)|( +)/g, '-').toLowerCase();

That explicitly checks for strings of spaces on either side of hyphens (the first pattern is also designed to consume trailing space), consuming exactly one hyphen in the process. If a hyphen already exists surrounded by spaces, that hyphen is included in the match, so when a hyphen is written, it is simply a "replacement"; in this case, the spaces are simply removed, and the hyphen is re-created by the replace operation because it is captured as part of the expression.


Include hyphens in the regexp.

str.replace(/[ -]+/g, '-').toLowerCase();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜