Fred J. Fred J. -4 years ago 109
Javascript Question

check if string1 contains string2 without knowing which is 1 or 2

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

Answer Source

let string1 = 'body', string2 = 'bodyguard';
let string3 = 'bodyguard', string4 = 'body';

var controlString=function(str1,str2){
  if(str1.indexOf(str2)!==-1||str2.indexOf(str1)!==-1)
  return true;
  return false;
};
console.log(controlString(string1,string2));
console.log(controlString(string3,string4));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download