简体   繁体   English

正则表达式在javascript中用双引号提供时不起作用

[英]regular expression not working when provided in double quotes in javascript

I am trying to use regular expession in javascript but it is not working. 我正在尝试在javascript中使用常规expession,但无法正常工作。 My custom control contains property called RegEx which is provided by user and I need to validate the input value against this regex. 我的自定义控件包含由用户提供的称为RegEx的属性,我需要针对此regex验证输入值。 As properties in JS will be in double quotes("") the regualr expression fails(case -1). 由于JS中的属性将用双引号(“”)引起,因此正则表达式将失败(情况-1)。 Case 2 succeeds thought both the cases regualr expression is same, the only difference is case- 1 it goes as double quotes. 案例2成功了,因为两个案例的正则表达式相同,唯一的区别是案例1作为双引号。 can somebody tell me why it is not working. 有人可以告诉我为什么它不起作用。 RegexExp="/^\\d{5}$/"- at my aspx page RegexExp =“ / ^ \\ d {5} $ /”-在我的aspx页面上

var value = "11111";
     if(value.toString().search($(element).attr('RegexExp')) != -1)
    {
        return true;
    }
    else
    {
        return false;
    }

  var reg = /^\d{5}$/;
     if(value.toString().search(reg) != -1)
    {
        return true;
    }
    else
    {
        return false;
    }

Do this instead: 改为这样做:

var reg = new RegExp($(element).attr('RegexExp'));

Update: you also need to strip the / characters, as these shouldn't be given to the RegExp constructor: 更新:您还需要去除/字符,因为不应将这些字符提供给RegExp构造函数:

var regexExp = $(element).attr('RegexExp');
var reg = new RegExp(regexExp.substring(1, regexExp.length - 1));

I assume that the code that you posted is part of the function from the return statements, but if it is not, your first problem is that return is not allowed to be used out side of functions. 我假设您发布的代码是return语句中函数的一部分,但如果不是,则您的第一个问题是不允许在函数外使用return

In any case, try the following. 无论如何,请尝试以下方法。 You can create a RegExp from a string by using its formal constructor 您可以使用字符串的正规构造函数从字符串创建RegExp

value.search(new RegExp($(element).attr('RegexExp')));

Also, you do not need to use toString() on value since it is already a string and your code is unnecessarily verbose. 另外,您不需要在value上使用toString() ,因为它已经是一个字符串,并且您的代码不必要地冗长。 The following is equivalent to your first if else statement 以下等效于您的第一个if else语句

return value.search(new RegExp($(element).attr('RegexExp'))) != -1;

Edit: 编辑:

If you want to be able to pass in an expression as "/[expression]/" or "/[expression]/gi", you can do the following: 如果希望以“ / [expression] /”或“ / [expression] / gi”形式传递表达式,则可以执行以下操作:

var toRegExp = function(regexString) {
    var expression   = regexString.substr(1),        // remove first '/'
        closingSlash = expression.lastIndexOf("/");  // find last '/'

    return new RegExp(
        // Expression: remove everything after last '/'
        expression.substr(0, closingSlash), 
        // Flags: get everything after the last '/'
        expression.substr(closingSlash+1)
    );
}

....

value.search( toRegExp($(element).attr('RegexExp')) );

First, don't use a custom attribute to hold a regular expression. 首先, 不要使用自定义属性来保存正则表达式。 Second, "RegexExp" is redundant — that's like saying "regular expression expression". 其次,“ RegexExp”是多余的-就像说“正则表达式expression”。 Third, to convert from a String to a RegExp, you have to wrap the string with new RegExp() ; 第三,要将字符串从RegExp转换,您必须使用new RegExp()来包装字符串; JavaScript is not weakly typed. JavaScript不是弱类型的。 That said, assuming that the regular expression isn't being set server-side, I'd recommend using jQuery's data API . 就是说,假设未在服务器端设置正则表达式,我建议使用jQuery的data API It has the added advantage that it can store regular expression objects directly. 它的另一个优点是可以直接存储正则表达式对象。

To set: 设置:

jQuery.data($(element).get(0), "regexp", /^\d{5}$/);

To get: 要得到:

jQuery.data($(element).get(0), "regexp");

But ultimately, what you really want is the jQuery Validation plugin . 但最终,您真正想要的是jQuery Validation插件 It does everything you need and then some. 它可以完成您需要的所有内容,然后执行一些操作。 Incidentally, it uses the data API internally to work its magic. 顺便说一句,它在内部使用数据API来发挥其魔力。

The /.../ syntax is used to declare a regular expression object in Javascript, so you shouldn't use that to specify a regular expression pattern, it should be just regexp="^\\d{5}$" as the attribute. /.../语法用于在Javascript中声明一个正则表达式对象,因此您不应使用该语法来指定正则表达式模式,它应该只是regexp="^\\d{5}$"作为属性。

The search method takes a regular expression object as parameter, so you have to create a regular expression object from the string that you get from the attribute: 搜索方法将正则表达式对象作为参数,因此您必须根据从属性获得的字符串创建一个正则表达式对象:

var reg = new RegExp($(element).attr('regexp'));
if (value.toString().search(reg) != -1) {

(You see the similarity with your second case?) (您看到与第二种情况的相似之处吗?)

Or as a single expression: 或作为单个表达式:

if (value.toString().search(new RegExp($(element).attr('regexp'))) != -1) {

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

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