views:

59

answers:

5

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?

+2  A: 

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)

Matti Virkkunen
+1: That, or fold spaces as the first step.
Chris
+2  A: 

Just match multiple whitespace characters.

s/\s+/-/g
Daniel DiPaolo
A: 

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

Oli
This worked perfectly!!
James Jeffery
You could add an additional `[\-]+` => `'-'` right at the end to replace multiple -s
Oli
+1  A: 

I use this:

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

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

Daniel Schaffer
A: 

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('-');
}
kennebec