0

Trying to check if 2 strings have matching word return true.

let 1st_string = chin, kore, span;
let 2nd_string = chin eng kore zulu

1st_string.split(',').indexOf(2nd_string) > -1 

I tried above code but always returns false. I need to return true as 2_nd string contains 2 matching words from 1st_string.

adiga
  • 34,372
  • 9
  • 61
  • 83
Zthrone
  • 35
  • 5
  • First JavaScript variable names should not start with a numeral and 1st_string and 2nd_string are not valid string it should be st_string = 'chin, kore, span'; the same for nd_string – Mario Feb 27 '19 at 16:32

3 Answers3

1

I think your second string will also contain a comma in between the words if yes then it is easy to achieve.

you can split the string 1 and 2 with a comma as delimiter like this

let firstString = 1st_string.split(',');
let secondString = 2nd_string.split(',');

after doing you will get the firstString and secondString variable as array then you can iterate the first array and check for duplicate using includes methods

for (let i in firstString) {
    if(secondString.includes(firstString[i])){
        //you can do whatever you want after finding duplicate here;
    }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
1

1st_string is not a valid variable name

split the first string and use Array.some() to see if the second string has any of the words in the resulting array :

let string_1 = 'chin, kore, span';
let string_2 = 'chin eng kore zulu';

const check = (str1, str2) => {
  return str1.split(',').some(word => str2.includes(word));
}

console.log(check(string_1, string_2))
Taki
  • 17,320
  • 4
  • 26
  • 47
1

Solved the names and values of the variables you can do the following

let first_string = 'chin, kore, span';
let second_string = 'chin eng kore zulu';
const array1 = first_string.split(',').map(string => string.trim());
const array2 = second_string.split(' ');

function exist(list1, list2) {
    for (const element of list1) {
        if (list2.includes(element)) {
            return true;
        }
    }

    return false;
}

const result = exist(array1, array2);

console.log(result);
Mario
  • 4,784
  • 3
  • 34
  • 50