JQuery - remove characters not matching regEx

I am trying to use jquery to validate forms.

This is the template that is allowed in the text box for the user.

var pattern = /^[a-zA-Z0-9!#$&%*+,-./: ;=?@_]/g;

If the user enters anything other than this, this should be replaced by "".

$(document).ready(function() {
  $('#iBox').blur(function() {
     var jVal = $('#iBox').val();
  if(jVal.match(pattern)) {
   alert("Valid");
  } else {
   alert("New "+jVal.replace(!(pattern),""));
                }
    });
  });
});

But the replace function does not work that way.

+3
source share
1 answer

Use a negative character class by writing ^immediately after the open square bracket:

/[^a-zA-Z0-9!#$&%*+,-./: ;=?@_]/g

Here it ^has a special meaning, which differs from the normal value that it has in regular expressions (usually it corresponds to the beginning of a line).

So your corrected code will look like this:

var pattern = /[^a-zA-Z0-9!#$&%*+,-./: ;=?@_]/g;
// ...
alert("New " + jVal.replace(pattern, ""));

, replace - . jVal, :

jVal = jVal.replace(pattern, "");
+5

Source: https://habr.com/ru/post/1784426/


All Articles