简体   繁体   中英

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?

For example:

match all pages: /pages/*

match a page called about: /pages/about

match all products that contain the string large: /products/*large*

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:-

/pages/* - uses .* for anything after '/pages/'

/\/pages\/.*/.test(str);

/pages/about - to match exactly '/pages/about'

/\/pages\/about/.test(str);

/products/*large* - to match '/products/' and then contains '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]);
  }
}

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM