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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With