Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Slugs from Titles?

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?

like image 960
James Jeffery Avatar asked Jun 07 '10 20:06

James Jeffery


People also ask

Should the slug be the same as the title?

You can make your page titles and slugs be whatever works best for your audience. For some sites having shorter page titles and slugs work best for their audience, for others longer or a mix is best. They do not need to be the same.

What does slug mean in advertising?

In the production process of print advertisements, a slug or slug line, refers to the "name" of a particular advertisement. Advertisements usually have several markers, ad numbers or job numbers and slug lines. Usually the slug references the offer or headline and is used to differentiate between different ad runs.


2 Answers

I use this:

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

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

like image 113
Daniel Schaffer Avatar answered Sep 22 '22 07:09

Daniel Schaffer


Just match multiple whitespace characters.

s/\s+/-/g
like image 29
Daniel DiPaolo Avatar answered Sep 21 '22 07:09

Daniel DiPaolo