[英]Regex to match string in current URL including wild card
What would be regex to match part of a URL using JavaScript and also include wildcards? 使用JavaScript匹配一部分URL并包含通配符的正则表达式是什么?
For example: 例如:
match all pages: /pages/*
匹配所有页面:
/pages/*
match a page called about: /pages/about
匹配名为about的页面:
/pages/about
match all products that contain the string large: /products/*large*
匹配所有包含字符串large的
/products/*large*
: /products/*large*
https://jsbin.com/toxemanewe/1/edit?js,console,output https://jsbin.com/toxemanewe/1/edit?js,console,output
I've did small changes in your code: 我对您的代码做了一些小的更改:
var patterns = [
'about',
'checkout',
'contact'
];
var str = 'https://myurl.com/page/about/';
for (i=0; i<patterns.length; i++) {
if ((new RegExp(patterns[i])).test(str)) {
//----^^^^^^^^^^^^^^^^^^^^^^^^^ look here how to instantiate the regex
console.log('matched pattern: ' + patterns[i]);
//----------------------------------^^^ look here plus sign instead comma
}
}
I've commented the updates. 我已经评论了更新。
Hope it helps. 希望能帮助到你。
As your question asks, the regex's to use for your 3 examples are:- 如您的问题所问,用于您的3个示例的正则表达式为:-
/pages/* - uses .* for anything after '/pages/' / pages / * -将。*用于'/ pages /'之后的任何内容
/\/pages\/.*/.test(str);
/pages/about - to match exactly '/pages/about' / pages / about-与“ / pages / about”完全匹配
/\/pages\/about/.test(str);
/products/*large* - to match '/products/' and then contains 'large' / products / * large * -匹配“ / products /”,然后包含“ large”
/\/products\/.*(?:large).*/.test(str);
and used in your example like 并在您的示例中使用
var patterns = [
'/pages/.*',
'/pages/about',
'/products/.*(?:large).*'
];
for (i=0; i<patterns.length; i++) {
if ((new RegExp(patterns[i])).test(window.location.href)) {
console.log('matched pattern ' + patterns[i]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.