我有两个urls
https://www.etsy.com/cartsdgsr <random characters after cart>
和
https://www.etsy.com/cart/<random numbers>/review
在js
页面的开头,我运行
if (document.URL.match("https://www.etsy.com/cart/*/review")) {
//run this code here
} else if (document.URL.match("https://www.etsy.com/cart*")) {
//run code here
}
但是*
没有工作,我该如何正确地写这个呢?
发布于 2021-01-08 02:47:04
以下是你所需要的:
if (document.URL.match(/^https:\/\/www\.etsy\.com\/cart\/\d+\/review/)) {
//run this code here
} else if (document.URL.match(/^https:\/\/www\.etsy\.com\/cart\w+/)) {
//run code here
}
正如philnash所提到的,您需要将一个RegExp
而不是一个字符串传递到String#match
函数中。
^
匹配字符串的开头。https:\/\/www\.etsy\.com\/cart\/
与https://www.etsy.com/cart/
完全匹配\d+
意味着它至少匹配一个数字(例如123
)。\/review
匹配精确的/review
\w+
至少匹配一个https://www.w3schools.com/jsref/jsref_regexp_wordchar.asp (例如l33t
)发布于 2021-01-08 02:37:31
String#match
可以与字符串匹配,但是如果您想要匹配一个模式,那么您将需要使用一个正则表达式。
在这种情况下,您需要在某个位置寻找一个或多个随机字符。因此,正则表达式看起来可能如下所示:
/^https:\/\/www\.etsy\.com\/cart\/[a-zA-Z0-9]+\/review$/
或者,如果您的意思是有随机数,您可以使用\d
而不是[a-zA-Z0-9]
,例如
/^https:\/\/www\.etsy\.com\/cart\/\d+\/review$/
和
/^https:\/\/www\.etsy\.com\/cart[a-zA-Z0-9]+$/
并适合您的示例代码:
if (document.URL.match(/^https:\/\/www\.etsy\.com\/cart\/[a-zA-Z0-9]+\/review$/)) {
//run this code here
} else if (document.URL.match(/^https:\/\/www\.etsy\.com\/cart[a-zA-Z0-9]+$/)) {
//run code here
}
https://stackoverflow.com/questions/65622633
复制相似问题