Regular expression - replace special characters, except dot

11,644

Use this for the regex instead:

 /[^\w.]|_/g

It reads any character that is not either alpha-numerical (which includes underbars) or dot, or that is an under bar.

update
But this is perhaps little more readable:

/[^0-9a-zA-Z.]/g
Share:
11,644
Horn Masgerter
Author by

Horn Masgerter

Updated on August 21, 2022

Comments

  • Horn Masgerter
    Horn Masgerter over 1 year
    $('#price').keyup(function(){
            $('#price').val($('#price').val().replace(/[_\W]+/g, "-"));
    })
    

    See it live at: http://jsfiddle.net/2KRHh/6/.

    This removes special characters, but how can I specify that it not replace dots?

  • sigpwned
    sigpwned almost 11 years
    I think you meant to add a "\" in the regular expression: /([^\w.])|_/g Also, why have you added a capture group around the [^\w.] character class?
  • Horn Masgerter
    Horn Masgerter almost 11 years
    but this replace also digits. This should allow digit 0-9 and numbers
  • Faust
    Faust almost 11 years
    @sigpwned: the capture group is not necessary.
  • Faust
    Faust almost 11 years
    @Horn: the \w means any char that is a number or a letter or _, while the ^ at the beginning of the character class means anything that is not one of these, so this will not replace digits.
  • Toto
    Toto almost 5 years
    Reread the question, they want to replace special characters except dot, so hyphen has to be removed.