gpt4 book ai didi

javascript - 检查 document.location 是否匹配特定模式

转载 作者:行者123 更新时间:2023-11-28 20:14:22 25 4
gpt4 key购买 nike

假设,如果 document.location 等于 http://www.example.comhttp://www.example.com/,我希望条件为 true example/anythinghere/,但如果位置不完全适合,则为 FALSE,例如 http://www.example.com/example/anythinghere/sdjfdfasdfaf 将返回 FALSE。

当然,我会写这样的内容:

if(document.location == "http://www.example.com/" || 
document.location == "http://www.example.com/example/*/")

但是,我知道好的星号通配符不起作用,并且作为正则表达式的业余爱好者,我无法找到正确的设置来寻找与模式的精确匹配。您对条件句的后半部分有何建议?

最佳答案

尝试以下操作:

 if(document.location == "http://www.example.com/" || 
/^http:\/\/www.example.com\/example\/[^\/]+\/?$/.test(document.location))

将测试您的 URL 是否与 http://www.example.com/ 完全匹配,或者是否使用正则表达式来查看是否与 http://www 匹配。 example.com/example/ANYTHING_HERE_EXCEPT_FORWARD-SLASH/

Regex101 Demo

关于javascript - 检查 document.location 是否匹配特定模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19430444/

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