简体   繁体   English

带星号的JavaScript模式匹配

[英]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? JS内置了一些带有星号的功能,还是我应该使用插件或其他功能?

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.*$/ . 在您的情况下,正则表达式可能是/^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 您可以尝试match()函数

 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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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