代码之家  ›  专栏  ›  技术社区  ›  Beingnin

使用regex验证jquery选择器语法

  •  2
  • Beingnin  · 技术社区  · 6 年前

    我试图用javascript编写一个regex表达式来验证字符串是否是有效的jquery选择器。这是严格的教育,不是我的任何项目的特殊要求。

    图案

    /^(\$|Jquery)\(('|")[\.|#]?[a-zA-Z][a-zA-Z0-9!]*('|")\)$/gi

    在下面的测试中它可以正常工作

    $("#id")//true

    $('.class')//true

    jquery('.class')//true

    jquery('div')//true

    我的问题是测试 $('#id") 还返回true,即在无效的JS中混合使用单引号和双引号。如何限制这一点。我们可以有条件正则表达式吗?

    const pattern = /^(\$|Jquery)\(('|")[\.|#]?[a-zA-Z][a-zA-Z0-9!]*('|")\)$/gi;
    
    [
    `$("#id")`, //true
    `$('.class')`, //true
    `jquery('.class')`, //true
    `jquery('div')`, //true
    ].forEach(str => console.log(pattern.test(str)));
    1 回复  |  直到 6 年前
        1
  •  5
  •   CertainPerformance    6 年前

    const re = /^(?:\$|Jquery)\((['"])[\.#]?[a-zA-Z][a-zA-Z0-9!]*\1\)$/gi;
    console.log(re.test(`$("#id")`))
    console.log(re.test(`$('#id")`))
    console.log(re.test(`$("#id')`))
    console.log(re.test(`$('#id')`))

    /^\$|Jquery...
    

    $

    '

    [\.|#]?
    

    . # [\.#]?