Wildcard matching of string JavaScript


We are required to write a JavaScript function that accepts two strings and a number n. The function matches the two strings i.e., it checks if the two strings contains the same characters. The function should return true if both the strings contain the same character irrespective of their order or if they contain at most n different characters, otherwise the function should return false.

Let's write the code for this function −

Example

const str1 = 'first string';
const str2 = 'second string';
const wildcardMatching = (first, second, num) => {
   let count = 0;
   for(let i = 0; i < first.length; i++){
      if(!second.includes(first[i])){
         count++;
      };
      if(count > num){
         return false;
      };
   };
   return true;
};
console.log(wildcardMatching(str1, str2, 2));
console.log(wildcardMatching(str1, str2, 1));
console.log(wildcardMatching(str1, str2, 0));

Output

The output in the console will be −

true
true
false

Updated on: 31-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements