[英]javascript regular expression not working
I am trying to validate a textbox to ensure that a URL is written inside (minus the "http://" part). 我正在尝试验证文本框,以确保在其中写入URL(减去“ http://”部分)。 Here is my code: 这是我的代码:
var isUrl;
var regex = new RegExp("^(?!http)(www\.)?(([a-z])+\.[a-z]{2,}(\.[a-z]{2,})?)");
var siteUrl = e.target.value;
if (siteUrl.match(regex)) {
isUrl = true;
}
else {
isUrl = false;
}
So my regular expression is ^(?!http)(www\\.)?(([az])+\\.[az]{2,}(\\.[az]{2,})?)
. 所以我的正则表达式是^(?!http)(www\\.)?(([az])+\\.[az]{2,}(\\.[az]{2,})?)
I was under the impression that this would do the following: 我的印象是,这将执行以下操作:
http
.. which it does correctly 不开始匹配任何http
..它不正确 www.
允许一个可选的www.
at the start 在开始时 In practice, the textbox accepts strings like "ashdiguasdf" and "aksjdnfa:://',~" which it should not do. 实际上,该文本框接受诸如“ ashdiguasdf”和“ aksjdnfa :: //',〜”之类的字符串,不应使用。 Can anyone explain why? 谁能解释为什么?
The main problem is that you're using the \\
character in a quoted string, which javascript will interpret as the start of a "control character" (such as \\n
for a newline, etc). 主要问题是您在带引号的字符串中使用\\
字符,而javascript会将其解释为“控制字符”的开头(例如\\n
表示换行符,等等)。
One option is to escape it by replacing \\
with \\\\
. 一种选择是通过将\\
替换为\\\\
来对其进行转义。
But the easiest solution is to use the following format... 但是最简单的解决方案是使用以下格式...
var regex = new RegExp(/^(?!http)(www\.)?(([a-z])+\.[a-z]{2,}(\.[a-z]{2,})?)/);
This also allows you to make it case insensitive (if you wish) by using the i
character at the end, like this... 这还允许您通过在结尾使用i
字符来使其不区分大小写(如果需要),如下所示...
var regex = new RegExp(/^(?!http)(www\.)?(([a-z])+\.[a-z]{2,}(\.[a-z]{2,})?)/i);
As an extra bit, you're using more capture groups than really necessary. 另外,您使用的捕获组超出了实际需要。 Your expression could also be written like this with the same result... 您的表达式也可以这样写,结果相同。
^(?!http)(?:www\.)?[a-z]+(?:\.[a-z]{2,}){1,2}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.