Reputation: 6019
In javascript, given a string "body" and another string "bodyguard", How can I return true
since one string is part of the other with out knowing their order of presentation to the code? i.e.
let string1 = 'body', string2 = 'bodyguard'
or
let string1 = 'bodyguard', string2 = 'body'
?
And without knowing if it is the first or the last part, so long as one string is completely part of the other, without knowing which is the longer of the two. thx
Upvotes: 0
Views: 1775
Reputation: 5020
let string1 = 'body', string2 = 'bodyguard';
let string3 = 'bodyguard', string4 = 'body';
var controlString=function(str1,str2){
return (str1.indexOf(str2)!==-1||str2.indexOf(str1)!==-1);
};
console.log(controlString(string1,string2));
console.log(controlString(string3,string4));
Upvotes: 1
Reputation: 1074138
Just check both ways:
if (str1.includes(str2) || str2.includes(str1)) {
// It's one of them
}
Or always check the longer one for the shorter one
let [longer, shorter] = str1.length > str2.length ? [str1, str2] : [str2, str1];
if (longer.includes(shorter) != -1) {
// It's one of them
}
(You used let
, so I assume it's okay to use destructuring assignment and String#includes
, as all are ES2015+.)
If you don't want to use String#includes
, though, str.indexOf(otherStr) != -1
does effectively the same thing.
Upvotes: 4
Reputation: 857
You can use this in Javascript :
var string1 = "body";
var string2 = "bodyguard";
if(string1.includes(string2) || string2.includes(string1)){
// DO WHAT YOU WANT
} else {
}
var string1 = "body";
var string2 = "bodyguard";
if(string1.includes(string2) || string2.includes(string1)){
document.getElementById("demo").innerHTML = "One string is part of another" ;
} else {
document.getElementById("demo").innerHTML = "No string is part of another" ;
}
<p id="demo"></p>
Upvotes: 0
Reputation: 1809
You can check if either string contains the other (not tested but should work):
if ((string1.indexOf(string2) !== -1) || (string2.indexOf(string1) !== -1)){
//do something
}
Upvotes: 1