JavaScript Compare two sentences word by word and return if they are substring of each other


The idea here is to take two strings as input and return true if a is substring of b or b is sub string of a, otherwise return false.

For example −

isSubstr(‘hello’, ‘hello world’) // true
isSubstr(‘can I use’ , ‘I us’) //true
isSubstr(‘can’, ‘no we are’) //false

Therefore, in the function we will check for the longer string, the one with more characters and check if the other is its substring or not.

Here is the code for doing so −

Example

const str1 = 'This is a self-driving car.';
const str2 = '-driving c';
const str3 = '-dreving';
const isSubstr = (first, second) => {
   if(first.length > second.length){
      return first.includes(second);
   }
   return second.includes(first);
};
console.log(isSubstr(str1, str2));
console.log(isSubstr(str1, str3a));

Output

The output in the console will be −

true
false

Updated on: 24-Aug-2020

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements