Search code examples
javascriptregexslug

Javascript Replace by Regex


I am using RegExp to make slug. I am saying replace all chars does not match the pattern like this:

str = str.replace(new RegExp('[^a-z0-9-]','g'), '');

It works but I need to ask if it is correct way/syntax/approach?

Thanks for any tips.


Solution

  • 1) You can write

    new RegExp('[^a-z0-9-]','g')
    

    as

    /[^a-z0-9-]/g
    

    The regular expression you wrote stands for the following:

    2) Whatever is inside [] means any of the characters not a sequence but when [^] the circumflex is present at the beginning it means NOT IN

    3) a-z stands for all characters from a to z (lowercase alphabet)

    4) 0-9 means 0 to 9 and the hyphen (-) at the end... well a hyphen.

    Therefore, what characters do you want to keep? If you want to keep only alpha-numeric then use /[^A-Za-z0-9]/g (this is the case sensitive version) or /[^a-z0-9]/gi for case insensitive

    the modifiers/flags: g = global, i= case insensitive

    A good place to look at: Mozilla MDN RegExp