【问题标题】:Trix validation of URL using regex使用正则表达式对 URL 进行 Trix 验证
【发布时间】:2019-09-26 10:14:13
【问题描述】:

我正在尝试更改验证模式以接受这些开始

https://
http://
https://www.
http://www. 
www.

这就是我现在拥有的:

inputElement.pattern = '^(https:?//|http:?//|http:?//www|https:?//www|www).+$';

它接受错误的情况,例如:

wwwsa.se
http://ww.

使用https://github.com/basecamp/trix/issues/624达到这一点

【问题讨论】:

    标签: javascript regex string trix


    【解决方案1】:

    你可以试试这个

    ^(?:(?:(?:https?:\/\/)?w{3})(?:[.].*|)|(?:https?:?\/\/(?!w{1,2}\.).*))$
    

    Regex Demo

    const regex = /^(?:(?:(?:https?:\/\/)?w{3})(?:[.].*|)|(?:https?:?\/\/(?!w{1,2}\.).*))$/i;
    const arr = ['https://','http://','https://www.','http://www.','www.','wwwsa.se','http://ww.','http://www.','ww.','www.','www//','www.g', 'http://wix']
    
    arr.forEach(str => {
      console.log(str, '\t\t' ,regex.test(str))
    })

    【讨论】:

    • http://https://之后不需要检查www,因为根据描述如果字符串从http://https://开始它已经有效。
    • 确实如此。因为网站可以有 wwwwws.com 什么的。
    【解决方案2】:

    你可能需要^(http(s)?://)|(www\.)之类的东西

    【讨论】:

    • 我得到这个是为了“\”。 38:60 错误不必要的转义字符:\。 no-useless-escape 和“www.test.se”不起作用
    • 你确定你使用正确吗,我刚刚试过(/^(http(s)?:\/\/)|(www\.)/).test('www.test.se')它返回true
    猜你喜欢
    • 2020-12-03
    • 2014-06-02
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2014-12-25
    • 2014-04-21
    相关资源
    最近更新 更多