gpt4 book ai didi

javascript - 为什么这个正则表达式总是返回 null?

转载 作者:行者123 更新时间:2023-12-02 18:53:17 25 4
gpt4 key购买 nike

我需要检查字符串中的类名。

我的字符串看起来像这样:

testing ui-li ui-li-static ui-btn-up-f ui-first-child ui-filter-hidequeue

我正在寻找ui-filter-hidequeue字符串中的任何位置 (!)。

这就是我正在尝试的。它总是返回 null ,尽管我试图匹配的字符串就在那里:

var classPassed = 'ui-filter-hidequeue',
classes = 'testing ui-li ui-li-static ui-btn-up-f ui-first-child ui-filter-hidequeue',
c = new RegExp('(?:\s|^)' + classPassed + '(?:\s|$)');

console.log( classes.match(c) ) // returns null

问题:
有人可以告诉我我的正则表达式做错了什么吗?

谢谢!

最佳答案

您需要\\s。字符串内的 \s 会对 s 进行转义,它不需要转义,并且计算结果仅为 "s"。 IE。当您使用文字正则表达式时,反斜杠会转义正则表达式字符;字符串也使用反斜杠来转义字符串字符。当您从字符串构建正则表达式时,您需要考虑这两层: \\ 是表示 \ 的字符串转义方式,然后是 \s 是表示空白的正则表达式转义方式。

正如其他评论所示,还有更好的方法来测试类状态。 :) 但我只是回答了直接错误。

关于javascript - 为什么这个正则表达式总是返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15605976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com