javascript – JS Regex url验证

栏目: JavaScript · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/30970068/js-regex-url-validation

我尝试验证带或不带http的url无论我做什么函数返回false.

我在这个网站上检查了我的正则表达式字符串:

http://regexr.com/

它看起来像我期待的那样.

function isUrlValid(userInput) {
        var regexQuery = "/(http(s)?://.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/";
        var url = new RegExp(regexQuery,"g");
        if (url.test(userInput)) {
            alert('Great, you entered an E-Mail-address');
            return true;
        }
        return false;
    }

我通过将.test更改为.match来解决问题并保持正则表达式不变.

我将函数更改为Match,使用斜杠及其工作进行更改:(http(s)?://.)

固定功能:

function isUrlValid(userInput) {
    var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
    if(res == null)
        return false;
    else
        return true;
}

翻译自:https://stackoverflow.com/questions/30970068/js-regex-url-validation


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Twitter Power

Twitter Power

Joel Comm / Wiley / 2009-02-17 / USD 24.95

"Arguably, one of the best tomes...Twitter Power is jam-packed with clever ways to start and dominate a marketplace." (Brandopia.typepad.com, March 23rd 2009) “For months I......一起来看看 《Twitter Power》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具