0

I want to analyse 2 strings and highlight the words that appear in both strings. So in the example below, apple and cherry would be highlighted. I guess you'd have to put them in an array and loop each array through the other to find matches among the two. I can't find any instructions on this specific task online, so if anyone knows how to do this I would love to know. Thanks

javaScript:

var str1 = "apple banana cherry damson";
var str2 = "apple elderberry cherry fig";

var array1 = str1.split(/\b/);
var array2 = str2.split(/\b/);

//compare arrays to find common words

$(commonWords).addClass('highlight');
user2014429
  • 2,497
  • 10
  • 35
  • 49
  • Possible solution $.inArray http://stackoverflow.com/questions/237104/array-containsobj-in-javascript – Rafal Jul 02 '14 at 16:15
  • 2
    well you already have the basic logic in mind... what is stopping you to try to code it ? Loops are a basic programming structure. Highlighting may get a bit trickier, but not that much neither... – Laurent S. Jul 02 '14 at 16:16

3 Answers3

1

Try this:

function getCommon(array1,array2){
    var result = new Array();
    for (i=0; i<array1.length; i++) {
        for (j=0; j<array2.length; j++) {
            if (array1[i] == array2[j] && jQuery.inArray(array1[i],result) == -1)
                result.push(array1[i]);
        }
    }
    return result;
}

var commonWords = getCommon(array1,array2);
alert(commonWords);

Working Fiddle : http://jsfiddle.net/aUAsG/

Burak
  • 5,252
  • 3
  • 22
  • 30
1

One line solution

$.grep(array1.map(function (e) { if (e && e.trim() && $.inArray(e,array2)) { return e } }), function (e) { if (e) {return e}})
xecgr
  • 5,095
  • 3
  • 19
  • 28
0
var str1 = "apple banana cherry damson";
var str2 = "apple elderberry cherry mapple applecake fruitcherry fig";
var splitStr = "\\b"+str1.split(/\s+/).join('\\b|\\b') + "\\b"
console.log(splitStr)
//output - \bapple\b|\bbanana\b|\bcherry\b|\bdamson\b 
str2.match(new RegExp(splitStr,'g'))
//output ["apple", "cherry"]

Tested with diff cases like - applecake fruitcherry mapple

Harpreet Singh
  • 2,651
  • 21
  • 31