9

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
  • The problem is the titles are created on the fly, using Javascript, to show the user what his URL will look like. It's for a social network. Commented Jun 7, 2010 at 21:08
  • 1
    JavaScript is a programming language, and it can do regex. What's the problem? Commented Jun 7, 2010 at 21:08

7 Answers 7

16

I use this:

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

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

1
  • 1
    Note: this also matches underscores. If you want it to replace them as well just go yourslug.replace(/[\W_]/g, '-')
    – Moe
    Commented Dec 24, 2021 at 19:48
5

Just match multiple whitespace characters.

s/\s+/-/g
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"!


Edit Jun 2024:

The above link seems dead, but can be accessed through the Web Archive here

The solution outlined on that page is:

function string_to_slug(str) {
  str = str.replace(/^\s+|\s+$/g, ''); // trim
  str = str.toLowerCase();
  
  // remove accents, swap ñ for n, etc
  var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
  var to   = "aaaaeeeeiiiioooouuuunc------";
  for (var i=0, l=from.length ; i<l ; i++) {
    str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
  }

  str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
    .replace(/\s+/g, '-') // collapse whitespace and replace by -
    .replace(/-+/g, '-'); // collapse dashes

  return str;
}
1
  • Great solution. Just change 'from' and 'to' vars to language you need. Commented Jul 10, 2015 at 8:54
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)

0
0

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

1
  • 1
    You could add an additional [\-]+ => '-' right at the end to replace multiple -s
    – Oli
    Commented Jun 7, 2010 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('-');
}
0

You can do it easily by using a simple package @smflow/seo-slug to generate slug from Title or any text: Github

How to generate

install the package: @smflow/seo-slug

npm install @smflow/seo-slug

Generate the slug

import { genSlug } from "@smflow/seo-slug";

const slug = genSlug("This is a blog title to generate slug");
console.log(slug); // this-is-a-blog-title-to-generate-slug1234

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.