1

全部 -

我正在使用以下代码(在线获取)来验证 URL。但是,由于 URL 变量 Network 中的括号,URL“http://www.yahoo.com?srch=news1&Network=[cnn]”无法返回 true。是否可以更新正则表达式以包含括号,或者我应该循环 URL 变量并删除括号?

 var webSiteUrlExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;

if (webSiteUrlExp.test(url)) {
      console.log("true");
      return true;
}
else {
     console.log("false");
      return false;
}
4

1 回答 1

1

That's because [ and ] are not valid characters within a URL. The browser will silently convert them to
%5B and %5D respectively, and the server will silently convert them back before passing it to the engine.

If you want to validate URLs with characters outside the normal range, you should first run it through some kind of escaping function.

于 2013-04-23T19:22:39.820 回答