Creating slugs from headlines?

I have everything to create bullets from names, but there is one problem. My RegEx replaces spaces with a hyphen. But when the user types "Hi there there" (a few spaces), the slug ends up as "Hi ----- there". When really it should be "Hi there."

Should I create a regular expression so that it replaces only space when there is a character on both sides?

Or is there an easier way to do this?

+5
source share
6 answers

I use this:

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

This replaces all occurrences of one or more non-alphanumeric characters of the same dash.

+6
source

.

s/\s+/-/g
+5

- -:

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

, , , ( , )

+2

[\s]+ '-', [^\w-] ''

0

, , .

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

All Articles