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

JavascriptWeb DevelopmentObject Oriented Programming

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 −


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


The output in the console will be −

Published on 24-Aug-2020 13:35:30