3

How to test if string contains on of the selected keywords?

For example

var keywords = 'small, big, large'
var string = 'big brown bear';

function wordInString(string, keywords){
  return new RegExp( '\\b' + keywords + '\\b', 'i').test(string);
}

The above only works for a single word, I need to be able to test multiple words, and exact match.

5
  • when you say multiple words, then order of words doesn't matter ryt? Commented Dec 9, 2016 at 20:23
  • That's correct, the order is not important. Commented Dec 9, 2016 at 20:24
  • Also if all are present only then you are required to return or even if single word is found then need to return? Commented Dec 9, 2016 at 20:26
  • split, each and IndexOf function of Javascript/jquery is your answer Commented Dec 9, 2016 at 20:26
  • @AJ it will,always be just one keyword that is matched or none for that matter, but never multiple. Commented Dec 9, 2016 at 20:27

5 Answers 5

6

Split the string into words, and use an array of keywords

function wordInString(string, keywords) {
    return string.split(/\b/).some(Array.prototype.includes.bind(keywords));
}

var keywords = ['small', 'big', 'large'];
var result1  = wordInString('big brown bear', keywords);   // true
var result2  = wordInString('great brown bear', keywords); // false
var result3  = wordInString('Big brown bear', keywords);   // false

console.log(result1, result2, result3);

ES5 (cross-browser) version

function wordInString(string, keywords) {
    return string.split(/\b/).filter(function(w) {
        return keywords.indexOf(w) !== -1;
    }).length > 0;
}

To return all the words

function wordInString(string, keywords) {
   return keywords.filter(function(x) { return this.includes(x) }, string.split(/\b/));
}

var keywords = ['small', 'big', 'large'];
var result1  = wordInString('big brown bear large', keywords); //  ["big", "large"]
var result2  = wordInString('great brown bear', keywords);     //  []
var result3  = wordInString('Big brown bear', keywords);       //  []

console.log(result1);
console.log(result2);
console.log(result3);

To return the first matching word or an empty string

function wordInString(string, keywords) {
	var r = "";
    string.split(/\b/).some( x => {
    	return r = keywords.includes(x) ? x : "";
    })
    return r;
}

var keywords = ['small', 'big', 'large'];
var result1  = wordInString('big brown bear large', keywords); //  "big"
var result2  = wordInString('great brown bear', keywords);     //  ""
var result3  = wordInString('Big brown bear', keywords);       //  ""

console.log(result1);
console.log(result2);
console.log(result3);

Sign up to request clarification or add additional context in comments.

4 Comments

I'm getting an error in firebug 'TypeError: Array.prototype.includes is undefined'
@Alko - your browser isn't up to date, Firefox supports includes from version 43 and up, added a ES5 version as well.
Ok, second ES5 version works fine, just one more problem, it returns true/false, I need to return the actual keyword if true, or an empty string if false.
That's not really what the question says, but okay, just the first keyword, or all keywords that match
1

Use an array of keywords, and loop through them:

var keywords = ['small', 'big', 'large'];

console.log( wordInString("big brown bear", keywords) );            // true
console.log( wordInString("it's small!", keywords) );               // true
console.log( wordInString("it's larger than the other", keywords) );// false
console.log( wordInString("it's black and red", keywords) );        // false

function wordInString(string, keywords){
  for(var i=0; i<keywords.length; i++){
    if(new RegExp( '\\b' + keywords[i] + '\\b', 'i').test(string)){
      return true;
    }
  }
  return false;
}

Comments

1

Returns matched word or preset string if not found.

function wordInString(string, keywords) {
  return string.split(/\b/).filter(word => keywords.some(w => w === word))[0] || 'empty';
}

var keywords = ['small', 'big', 'large'];
var result1  = wordInString('big brown bear', keywords);   // big
var result2  = wordInString('tiny bear', keywords); // empty
var result3  = wordInString('huge hairy bear', keywords);   // empty

console.log(result1, result2, result3);

Comments

0

Split the keywords and then search indexOf of keywords on the string.

var keywords = 'small, big, large'
var string = 'big brown bear';

function wordInString(string, keywords) {
  return keywords.split(',').some(function(keyword) {
    return string.indexOf(keyword.trim()) == -1 ? false : true
  });
  //return new RegExp('\\b' + keywords + '\\b', 'i').test(string);
}

console.log(wordInString(string, keywords))
console.log(wordInString(string, "xyz, abc"))
console.log(wordInString("'a large bear'", "large, none"))

Comments

0

Here is a different solution using map,reduce functions and logical operators.

var keywords = 'small, big, large'
var test1  = testString('big brown bear', keywords);   //big
var test2  = testString('great brown bear', keywords); // empty
var test3  = testString('Big brown bear', keywords);   // empty
function wordInString(string, keywords){
  return new RegExp( '\\b' + keywords + '\\b').test(string);
}

function testString(string,keywords){
    var word='empty';
    var result=keywords.split(',').map(function(item){
        if(wordInString(string,item.trim())==true)
            word=item.trim();
        return wordInString(string,item.trim());  
    }).reduce(function(curr,prev){
        return curr || prev;
    });
    return word;
 }
console.log(test1)
console.log(test2)
console.log(test3)

1 Comment

@Alko, please have a look at my answer.

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.