Abhishek kamal
Abhishek kamal

Reputation: 482

How to match for a string from an original string?

I want to match a string from an original string
Eg :
Assume that the orginal string is
"THE QUICK BROWN FOX JUMPS OVER A LAZY DOG."
and another string is
"QUICK OVER A DOG"
So If the words of the above string present in original string then it should return true. How can I do this ?

I have used the method indexOf(filter) > -1
It is working only if I give the continuous string like
"BROWN FOX"
but If I give "BROWN JUMPS" as a string then It is not working.

var string_1 = "QUICK BROWN";
var string_2 = "QUICK FOX";
// this returns true
if (original.toUpperCase().indexOf(string_1) > -1) {
    console.log("true");
} else {
    console.log("false");
}

// this returns false
if (original.toUpperCase().indexOf(string_2) > -1) {
    console.log("true");
} else {
    console.log("false");
}

So How can I match the string from original string ?

Upvotes: 1

Views: 93

Answers (3)

sumit
sumit

Reputation: 15464

you can do it using the following array tricks. Just check if all elements of new array is in original array too.

let str1='THE QUICK BROWN FOX JUMPS OVER A LAZY DOG';
let str2='THE FOX JUMPS';
 
let arr1=str1.split(" ");
let arr2=str2.split(" ");

console.log(arr2.filter( a => arr1.includes(a)).length===arr2.length);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371193

I'd match all word characters in both strings, to get an array of words, and put the original string's words (the one to search through) into a Set. Then check whether .every one of the other words exists in the Set:

const orig = "THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.";
// if the strings may not have any words in them at all,
// then alternate with the empty array, since the match will be null:
const origWordsSet = new Set(orig.match(/\w+/g) || []);
const verify = str => (str.match(/\w+/g) || []).every(word => origWordsSet.has(word));

console.log(
  verify("QUICK OVER A DOG"),
  verify("QUICK BROWN"),
  verify("QUICK FOX"),
  verify("FOO")
);

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386868

If in order, you could take indexOf and iterate all words by taking an index.

const 
    checkInOrder = (haystack, needle, index = 0) => 
        needle.split(' ').every(w => (index = haystack.indexOf(w, index)) !== -1);
    checkWithoutOrder = (haystack, needle) => 
        needle.split(' ').every(w => haystack.includes(w));

console.log(checkInOrder("THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.", "QUICK OVER DOG"));
console.log(checkInOrder("THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.", "QUICK OVER some DOG"));
console.log(checkWithoutOrder("THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.", "DOG OVER "));
console.log(checkWithoutOrder("THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.", "DOG OVER some"));

Upvotes: 1

Related Questions