Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript string.replace against negative list

I know it's preferable to use a whitelist when dealing with regexp, but due to client requirement I can't do that. They don't want us to prevent the user from entering special characters - we need to allow them to enter them, and then strip them out before saving.

So say I have something like this:

$('#clickMe').click(function() {
    var test = $('#pizza').val();
    var pattern = /[a-z][0-9]/;
    if (!pattern.test(test)) {
        console.log("not pass: " + test);
    }
    else {
        console.log("passes");
    }
})

How can I do a string.replace() and replace any characters in test that aren't in the pattern?

ETA: here's a fiddle; if you enter something like Esther (test*&^) pizza in the input field, I want it to return Esther test pizza.

like image 470
EmmyS Avatar asked Dec 14 '25 16:12

EmmyS


1 Answers

Define your regex like this:

var test = $('#pizza').val();
var pattern = /[^\w\s]+/g;
if (pattern.test(test)) {
    console.log("not pass: " + test);
    var cleanVal = test.replace(pattern, '');   
    // set cleanVal to wherever you want
    $('#pizza').val(cleanVal);
}
else {
    console.log("passes");
}
like image 54
anubhava Avatar answered Dec 17 '25 07:12

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!