Creating Slugs from Titles?

可紊 提交于 2019-12-01 17:24:08

I use this:

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

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

Just match multiple whitespace characters.

s/\s+/-/g

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)

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"!

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

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