2

I am trying to compare words in strings. This is what i want to do:

var string1 = "Action, Adventure, Comedy";
var string2 = "Action Horror";

if (string1 have a word from string 2 == true)
{
    alert("found!");
}

I have tried match() but in my situation, it tries to find "Action Horror" instead of "Action" and "Horror" words.

Eren
  • 183
  • 2
  • 13
  • http://stackoverflow.com/a/21081760/4689622 – Nimesh Gami Feb 27 '16 at 09:14
  • Possible duplicate of [JavaScript/jQuery - How to check if a string contain specific words](http://stackoverflow.com/questions/5388429/javascript-jquery-how-to-check-if-a-string-contain-specific-words) – mcy Feb 27 '16 at 10:50

3 Answers3

1

You can do something like this using match() and reduce()

var string1 = "Action, Adventure, Comedy";
var string2 = "action Horror";

var strArr = string1.match(/\b\w+?\b/g)
  //getting all words from string one
  .map(function(v) {
    return v.toLowerCase();
  });
//converting strings to lower case for ignoring case

var res = string2.match(/\b\w+?\b/g)
  // getting words from second string
  .reduce(function(a, b) {
    return a || strArr.indexOf(b.toLowerCase()) != -1;
    //checking string in first word  array
  }, false);
  // also set initial value as false since no strings are matched now

console.log(res);

Or

var string1 = "Action, Adventure, Comedy";
var string2 = "action Horror";

var res = string2.match(/\b\w+?\b/g)
  // getting words from second string
  .reduce(function(a, b) {
    return a || new RegExp('\\b' + b + '\\b', 'i').test(string1);
    //checking string in first string
  }, false);
  // also set initial value as false since no strings are matched now

console.log(res);

Refer : JavaScript/jQuery - How to check if a string contain specific words

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

Solution with String.split, String.indexOf and Array.foreach functions:

var string1 = "Action, Adventure, Comedy, Horror";
    var string2 = "Action Horror";

    var str1_arr = string1.split(', ');
    str1_arr.forEach(function (v) {
        if (string2.indexOf(v) !== -1) {
            console.log("string '"+ v +"'(from string1) was found in string2 in position " + string2.indexOf(v));
        }
    });

// the output:
string 'Action'(from string1) was found in string2 in position 0
string 'Horror'(from string1) was found in string2 in position 7

https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/split https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
-1

Declare two sets:

    var Set set1,ser2;

Copy string1 into set1 and string2 into set2

(Not sure how to do this). Then have:

var intersection = new Set([x for (x of set1) if (set2.has(x))]);

    if intersection.prototype.size>0

There are words common to both strings (and sets).

Arif Burhan
  • 507
  • 4
  • 12