使用正则表达式查找字符串中的不匹配字符

find mismatch character in the string with regular expression

本文关键字:不匹配 字符 字符串 正则表达式 查找      更新时间:2023-09-26

当文本输入/粘贴文本时,我必须在文本区域找到并向用户显示除键盘字符以外的任何特殊字符,下面我解释了我尝试做什么!请尽快帮助我?

if ($(txtMessage).val().trim() != "") {
         var pattern = "^[a-zA-Z0-9~`!@#$%^&*()_+-={}|:;<>,.?'/']+$";
         for(var i=0;i<$(txtMessage).val().length;i++){
             var subStr=$(txtMessage).val().substring(0, i);
             if(!subStr.match(pattern)){
                 $('#customDailogBox')
                    .text(
                            "You have entered or paste "+subStr.substring(i, i)+"input  characters are not supported characters!!!..");
             }
         }

更改循环条件和子字符串函数

 for(var i=1;i=<$(txtMessage).val().length;i++){
         var subStr=$(txtMessage).val().substr(i,1);
         if(!subStr.match(pattern)){
             $('#customDailogBox').text("You have entered or paste "+subStr.substring(i, i)+"input  characters are not supported characters!!!..");
         }
}

或者您也可以使用正则表达式匹配整个字符串一次

var unmatched_characters = $(txtMessage).val().match(/[^a-zA-Z0-9~`!@#$%^&*()_+-={}|:;<>,.?'/']/g);
if (unmatched_characters.length>0){
     $('#customDailogBox').text("You have entered or paste some characters that are not supported !!!..");
}