Creating Slugs from Titles?

↘锁芯ラ 提交于 2019-12-01 16:12:46

问题


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?


回答1:


I use this:

yourslug.replace(/\W+/g, '-')

This replaces all occurrences of one or more non-alphanumeric characters with a single dash.




回答2:


Just match multiple whitespace characters.

s/\s+/-/g



回答3:


It might be the easiest to fold repeated -s into one - as the last step:

replace /-{2,}/ by "-"

Or if you only want this to affect spaces, fold spaces instead (before the other steps, obviously)




回答4:


Daniel's answer is correct.

However if somebody is looking for complete solution I like this function,

http://dense13.com/blog/2009/05/03/converting-string-to-slug-javascript/

Thanks to "dense13"!




回答5:


I would replace [\s]+ with '-' and then replace [^\w-] with ''




回答6:


You may want to trim the string first, to avoid leading and trailing hyphens.

function hyphenSpace(s){
    s= (s.trim)? s.trim(): s.replace(/^\s+|\s+$/g,'');
    return s.split(/\s+/).join('-');
}


来源:https://stackoverflow.com/questions/2993119/creating-slugs-from-titles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!