3

Hello, I'm trying to make a simple matching game in javascript.

If the the user inserts the text president goes crazy in any way that contains every strings in word_tmp, then the word_tmp becomes true, and if he misses one string then it becomes false.

word_tmp = ['president', 'goes', 'crazy'];

// string 1 contains the president, goes and crazy at one string
string1 = 'president goes very crazy'; // should output true

// string 2 doesn't contain president so its false.
string2 = 'other people goes crazy'; // should output false

How can I accomplish this?

3

3 Answers 3

1

Try this:

var word_tmp = ['president', 'goes', 'crazy'];
var string1 = 'president goes very crazy';

var isMatch = true;
for(var i = 0; i < word_tmp.length; i++){
    if (string1.indexOf(word_tmp[i]) == -1){
        isMatch = false;
        break;
    }
}

return isMatch //will be true in this case
Sign up to request clarification or add additional context in comments.

1 Comment

simplest one maybe if others need it.
1

You can do it with simple reduce call:

word_tmp.reduce(function(res, pattern) {
  return res && string1.indexOf(pattern) > -1;
}, true);

The same code, wrapped in a function:

var match_all = function(str, arr) {
  return arr.reduce(function(res, pattern) {
    return res && str.indexOf(pattern) > -1;
  }, true);
};

match_all(string1, word_tmp); // true
match_all(string2, word_tmp); // false

But this solution won't work for you if you want to match whole words. I mean, it will accept strings like presidential elections goes crazy, because president is a part of the word presidential. If you want to eliminate such strings as well, you should split your original string first:

var match_all = function(str, arr) {
  var parts = str.split(/\s/); // split on whitespaces
  return arr.reduce(function(res, pattern) {
    return res && parts.indexOf(pattern) > -1;
  }, true);
};

match_all('presidential elections goes crazy', word_tmp); // false

In my example I'm splitting original string on whitespaces /\s/. If you allow punctuation marks then it's better to split on non-word characters /\W/.

Comments

0
var word_tmp = ['president', 'goes', 'crazy'];
var str = "president goes very crazy"

var origninaldata = str.split(" ")
var isMatch = false;
for(var i=0;i<word_tmp.length;i++) {
   for(var j=0;j<origninaldata.length;j++) {
      if(word_tmp[i]==origninaldata[j])
        isMatch = true;
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.