Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 one string is a substring of the other, otherwise return false.
For example:
isSubstr('hello', 'hello world') // true
isSubstr('can I use', 'I us') // true
isSubstr('can', 'no we are') // false
In the function, we check which string is longer and then verify if the shorter string exists as a substring within the longer one.
Syntax
const isSubstr = (first, second) => {
if (first.length > second.length) {
return first.includes(second);
}
return second.includes(first);
};
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, str3));
Output
true false
How It Works
The function compares string lengths and uses the includes() method to check if the shorter string exists within the longer one. In the first case, '-driving c' is found in 'This is a self-driving car.', so it returns true. The second case returns false because '-dreving' (with a typo) doesn't exist in the original string.
Additional Examples
console.log(isSubstr('hello', 'hello world')); // true
console.log(isSubstr('world', 'hello world')); // true
console.log(isSubstr('javascript', 'java')); // true
console.log(isSubstr('python', 'javascript')); // false
console.log(isSubstr('', 'any string')); // true (empty string)
Output
true true true false true
Conclusion
This approach efficiently determines substring relationships by comparing lengths first, then using the built-in includes() method. It works bidirectionally, checking if either string contains the other as a substring.
