Dennis J
Dennis J

Reputation: 186

How do I split a string and then match them with another string

Let's sat I have the sentence "I like cookies" and the sentence "I_like_chocolate_cookies". How do I split the string "I like cookies" and check if the words exists in the second sentence?

Upvotes: 1

Views: 128

Answers (4)

Abraham
Abraham

Reputation: 20694

Here's some sample code:

str1 = 'I like cookies'
str2 = 'I_like_chocolate_cookies'
// We convert the strings to lowercase to do a case-insensitive check. If we
// should be case sensitive, remove the toLowerCase().
str1Split = str1.toLowerCase().split(' ')
str2Lower = str2.toLowerCase()
for (var i = 0; i < str1Split.length; i++) {
  if (str2Lower.indexOf(str1Split[i]) > -1) {
    // word exists in second sentence
  }
  else {
    // word doesn't exist
  }
}

Hope this helps!

Upvotes: 0

Aesthete
Aesthete

Reputation: 18858

var foo = "I_like_chocolate_cookies";
var bar = "I like chocolate cookies";

foo.split('_').filter(function(elements) {
  var duplicates = []
  if(bar.split().indexOf(element) != -1) {
    return true;
  }
});

Upvotes: 0

Prinzhorn
Prinzhorn

Reputation: 22518

Like this

var words = "I like cookies".replace(/\W/g, '|');
var sentence = "I_like_chocolate_cookies";

console.log(new RegExp(words).test(sentence));

https://tinker.io/447b7/1

Upvotes: 1

Steen
Steen

Reputation: 2887

like this?

var x ="i like grape";
var c ="i_don't_like";
var xaar = x.split(' ');
for(i=0;i<xaar.length;i++){
if(c.indexOf(xaar[i])>-1) console.log(xaar[i]);

}

Upvotes: 0

Related Questions