Creating Slugs from Titles?

Jam*_*ery 6 javascript regex slug

I have everything in place to create slugs from titles, but there is one issue. My RegEx replaces spaces with hyphens. But when a user types "Hi     there" (multiple spaces) the slug ends up as "Hi-----there". When really it should be "Hi-there".

Should I create the regular expression so that it only replaces a space when there is a character either side?

Or is there an easier way to do this?

Dan*_*fer 7

我用这个:

yourslug.replace(/\W+/g, '-')
Run Code Online (Sandbox Code Playgroud)

这将使用单个短划线替换所有出现的一个或多个非字母数字字符.


Dan*_*olo 5

只需匹配多个空格字符.

s/\s+/-/g
Run Code Online (Sandbox Code Playgroud)


Mat*_*nen 2

最后一步将重复的-s 折叠成一个可能是最简单的:-

replace /-{2,}/ by "-"
Run Code Online (Sandbox Code Playgroud)

或者,如果您只想影响空格,请改为折叠空格(显然,在其他步骤之前)