Horn Masgerter
Horn Masgerter

Reputation: 193

Regular expression - replace special characters, except dot

$('#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?

Upvotes: 5

Views: 19538

Answers (2)

Gcpt
Gcpt

Reputation: 51

It's a bit old now but in case someone still need it, Faust's answer didn't work for me (I tried to change a file's name to use it in a URL) so here's the solution I found :

preg_replace('/[^A-Za-z0-9.\-]/', '', $string);

Upvotes: 0

Faust
Faust

Reputation: 15394

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

Upvotes: 7

Related Questions