3

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.

3 Answers 3

2

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");
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you wanted to remove the unwanted characters

var test = test.replace(/[^a-z0-9]/gi, ""); //g means all, i means case insensitve

Comments

0

I think the correct pattern is /[a-z0-9]/, not /[a-z][0-9]/.

The best solution would involve changing a little the expression :

var cleanString = test.replace(/[^a-z0-9]/g,'');

If you can't, then you can do this :

var cleanString = test.match(/[a-z0-9]/g).join('');

4 Comments

I tried /[a-z0-9]/, and it allowed 123@ and 1@23 to pass.
You mean if you use the test function ? In that function you must make the regex cover the whole string : /^[a-z0-9]*$/
This will fail on capital letters.
@JustinMorgan That's the pattern of the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.