8

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?

Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115
James Jeffery
  • 3,365
  • 4
  • 19
  • 13

6 Answers6

15

I use this:

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

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

Daniel Schaffer
  • 56,753
  • 31
  • 116
  • 165
  • Note: this also matches underscores. If you want it to replace them as well just go `yourslug.replace(/[\W_]/g, '-')` – Moe Dec 24 '21 at 19:48
5

Just match multiple whitespace characters.

s/\s+/-/g
Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115
3

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

EGL 2-101
  • 1,203
  • 8
  • 17
2

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
  • 63,558
  • 9
  • 127
  • 159
0

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

Oli
  • 235,628
  • 64
  • 220
  • 299
  • 1
    You could add an additional `[\-]+` => `'-'` right at the end to replace multiple -s – Oli Jun 07 '10 at 21:31
0

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
  • 102,654
  • 32
  • 106
  • 127