Search code examples
javascriptregexslug

JavaScript Regex replace if more than n occurence


I have a Regex which replaces all non-alphanumeric characters with a hyphen.

slugName = $(this).val().replace(/[^a-z0-9]/gi, '-');

This works as it should, however since this is generated from user input, I may end up with a result like my-awesome-title---stuff which could have been entered as my awesome title & stuff

As you can see, I now have three consecutive hyphens which don't really appeal as a pretty URL.

Is there some way that I can replace such occurrences if there is a consecutive line of hyphens?


Solution

  • Something like this:

    slugName = $(this).val().replace(/[^a-z0-9]+/gi, '-');
    

    Should replace one or more instance of characters which are non-alphanumeric with 1 hyphen. The '+' in this case means one or more instance of.