简体   繁体   中英

JavaScript Pattern Matching with Asterisks

I want to make something that would check if a string like this:

https://www.example.com/page

Is equal to:

http*//*example.com/*

Or something like this. Is there something built in to JS that does this with asterisks, or should I use a plugin or something?

There's nothing built in that does what you've literally described. But look at regular expressions , which are the generalized version. The regular expression in your case would probably be /^http.*\\/\\/.*example\\.com.*$/ .

Example:

 var rex = /^http.*\\/\\/.*example\\.com.*$/; function test(str) { console.log(str, rex.test(str)); } test("https://www.example.com/page"); // true test("ttps://www.example.com/page"); // false 

You can try match() function

 let str = 'https://www.example.com/page'; let strMatches = str.match( /http([\\s\\S]*?)\\/\\/([\\s\\S]*?)example.com([\\s\\S]*?)/ ); let result = document.querySelector('#result'); if( strMatches!= null && strMatches.length > 0 ){ result.innerHTML = 'Match'; } else { result.innerHTML = 'Mismatch'; } 
 <div id="result"></div> 

I was able to create a function that does this, but thank you all for your answers. I will post the code below.

var wildcardCheck = function(i, m) {
   var regExpEscape = function(s) {
       return s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
   };
   var m = new RegExp('^' + m.split(/\*+/).map(regExpEscape).join('.*') + '$');
   return i.match(m) !== null && i.match(m).length >= 1;
};

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