【问题标题】:How to convert the charactes to regex?如何将字符转换为正则表达式?
【发布时间】:2014-09-22 03:23:29
【问题描述】:
var spclChrs="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";

/*Accepted Characters*/
var id = $(this).attr('id');
var textVal = $("#" + id).val();
$("#" + id).css({ "background": "", "border": "" });
for (var i = 0; i < textVal.length; i++) {
    if (spclChrs.indexOf(textVal.charAt(i)) == -1) {
        if (sessionLang == 0) {
            $().toastmessage('showErrorToast', "Invalid  character(s) entered.");
        }
        if (sessionLang == 1) {
            $().toastmessage('showErrorToast', "Los caractere(s) entraron.");
        }
        $("#" + id).css({ "background": "#FFCECE", "border": "1px solid red", });
        textVal = textVal.slice(0, -1);
        $("#" + id).val(textVal);
        return false;
    }
}

我对 keyup 和 keydown 事件的文本框进行了以下验证。我接受在我的变量“spclChars”中指定的字符。而不是手动指定字符,我如何通过 Ragex 做到这一点,保持我的代码不变。

【问题讨论】:

  • 你的意思是你想让代码生成"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"
  • 我想你想要这个:var spclchars = [a-zA-Z0-9\-\_]
  • 是的。但是 spclChars.indexOf() 应该可以工作。
  • @Mr_Green 是的。由于我使用的是 spclchars .indexOf() 它不起作用。
  • var spclchars = Array.apply(0,Array(256)).reduce(function(s,_,i){ var v=String.fromCharCode(i); return /[a-zA-Z0-9\-\_]/.test(v) ? s+v : s }, "")

标签: javascript jquery regex


【解决方案1】:

我想说以下是你所追求的:

// Regular expression to check against
// [^ creates a negative character class, saying that it only looks for characters NOT defined in this class
// \w = Any (english) alphanumerical characters (a-zA-Z0-9)
// -_
// ] end of class
// This [^\w-_] means any character that isn't a-zA-Z0-9-_.
// g = global flag
var reg = /[^\w-_]/g;   

var id = $(this).attr('id');
var textVal = $("#" + id).val();
$("#" + id).css({ "background": "", "border": "" });

// Test the string towards the regular expression
// true = fits the expression (Have used special characters)
// false = Doesn't fit (only used a-zA-Z0-9-_)
if (reg.test(textVal)) {
    if (sessionLang == 0) {
        $().toastmessage('showErrorToast', "Invalid  character(s) entered.");
    }

    if (sessionLang == 1) {
        $().toastmessage('showErrorToast', "Los caractere(s) entraron.");
    }
    $("#" + id).css({ "background": "#FFCECE", "border": "1px solid red", });
    textVal = textVal.slice(0, -1);
    $("#" + id).val(textVal);
    return false;

PS:您的示例末尾似乎缺少一些代码:)

【讨论】:

  • 如果这回答了您的问题,请将其标记为已回答
  • 我必须循环检查并分配其他条件。
猜你喜欢
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
  • 2012-01-28
  • 1970-01-01
  • 2022-11-18
  • 2017-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多