JavaScript Pattern Matching with Asterisks

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



JavaScript Pattern Matching with Asterisks



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



https://www.example.com/page


https://www.example.com/page



Is equal to:



http*//*example.com/*


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?





Just to be precise, what you're looking for is 'wildcard matching', and the * is the wildcard. You can't do that out of the box, but have a look at the answer below for a solution with regex
– Fabio Lolli
Aug 6 at 16:26


*




3 Answers
3



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([sS]*?)//([sS]*?)example.com([sS]*?)/ );

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) \()[]^$+*?.]/g, '\$&');
;
var m = new RegExp('^' + m.split(/*+/).map(regExpEscape).join('.*') + '$');
return i.match(m) !== null && i.match(m).length >= 1;
;






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard