简体   繁体   English

JQuery - 删除不匹配regEx的字符

[英]JQuery - remove the chars not matching regEx

I am trying to use jquery for validating forms. 我正在尝试使用jquery来验证表单。

This is the pattern that is allowed in a text box for a user. 这是用户的文本框中允许的模式。

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

If the user types anything else other than this then that has to be replaced with a "". 如果用户键入除此之外的任何其他内容,则必须用“”替换。

$(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 this way. 但是替换功能不能以这种方式工作。

Use a negated character class by writing a ^ immediately after the opening square bracket: 通过在开始方括号后面立即写^使用否定字符类

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

Here the ^ has a special meaning that is different from the normal meaning it has in regular expressions (normally it matches the start of the line). 这里^具有特殊含义,与正则表达式中的正常含义不同(通常它与行的开头匹配)。

So your corrected code would look like this: 所以你纠正的代码看起来像这样:

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

Also note that calling replace doesn't actually change the original string - it returns a modified copy of the string. 另请注意,调用replace实际上并不会更改原始字符串 - 它会返回字符串的修改后的副本。 If you want to modify the value of jVal you will need to reassign to it: 如果要修改jVal的值,则需要重新分配给它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM