regExpression.test [英] regExpression.test

查看:45
本文介绍了regExpression.test的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var regExpression = /^([a-zA-Z0-9_\-\.]+)$/; //line 2
//// var regExpression = "/" + "^([a-zA-Z0-9_\-\.]+)$" + "/"; //line 3
alert (regExpression.test("11aa"));

以上代码工作正常。

但如果我们更换第2行第3行然后它不工作

为什么?
i我的情况就像我想通过追加来创建var(动态表达式)所以我该怎么做?

The above code is working fine.
But if we replace line 2 by line 3 then it is not working
why? i am in a situation like I want to create the var only by appending(the expression come dynamically) so what should i do?

推荐答案

第3行将 regExpression 设置为字符串。字符串没有 test 方法。您需要将字符串转换为RegExp。

Line 3 sets regExpression to a string. Strings does not have a test method. You need to turn the string into a RegExp.

var regExpression = new RegExp("^([a-zA-Z0-9_\\-\\.]+)$");

省略斜杠,因为它们不是正则表达式本身的一部分。

Omit the slashes, as they are not part of the regexp itself.

这篇关于regExpression.test的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆