Creating Slugs from Titles?
I have everything in place to create slugs from titles, but there is one issue. My 开发者_如何学GoRegEx 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?
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
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"!
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)
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('-');
}
精彩评论