JavaScript URL 通配符表示任何数字或字母
JavaScript URL wildcard to mean any number or letter
我有两个网址
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
}
但是 *
不工作我该如何正确地写这个?
String#match
can match against a string, but if you want to match against a pattern then you will want to reach for a regular expression.
在这种情况下,您正在某个地点寻找一个或多个随机字符。所以你的正则表达式看起来像:
/^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
}
这是您需要的:
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+
匹配至少一个 word character(例如 l33t
)
我有两个网址
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
}
但是 *
不工作我该如何正确地写这个?
String#match
can match against a string, but if you want to match against a pattern then you will want to reach for a regular expression.
在这种情况下,您正在某个地点寻找一个或多个随机字符。所以你的正则表达式看起来像:
/^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
}
这是您需要的:
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+
匹配至少一个 word character(例如l33t
)