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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With