Javascript: multiple expressions in an array when searching for strings

I am currently working with Javascript and now I am looking for a way to check if a variable contains at least one string. However, I looked at the previous questions but did not contain what I am looking for. I have a function here:

function findCertainWords() 
{
    var t = {Some text value};
    if (t in {'one':'', 'two':''}) 
       return alert("At least one string is found. Change them."), 0;
    return 1
}

      

The variable a is text written by the user (such as a comment or message).

I want to check if the user has written a specific word in it and return a warning message to delete / edit that word. While my writing function works, it only works when the user writes down that word exactly as I write in my variable ( "Three" != "three"

). I want to improve my functionality so that it also finds case insensitivity ( "Three" == "three"

) and part of words (like "thr" of "three"). I tried to express a type expression *

, but it didn't work.

It would be better if each expression could be written into one function. Otherwise, I may need help combining the two functions.

+3


source to share


2 answers


Use indexOf

to check if a string contains another string. Use .toLowerCase

to convert it to one case before comparing.

function findCertainWords(t) {
    var words = ['one', 'two'];
    for (var i = 0; i < words.length; i++) {
        if (t.toLowerCase().indexOf(words[i]) != -1) {
            alert("At least one string was found. Change them.");
            return false;
        }
    }
    return true;
}

      



Another way is to turn the array into a regexp:

    var regexp = new RegExp(words.join('|'));
    if (regexp.test(t)) {
        alert("At least one string was found. Change them.");
        return false;
    } else {
        return true;
    }

      

+3


source


You can use Array.some

withObject.keys



if(Object.keys(obj).some(function(k){
   return ~a.indexOf(obj[k]);
})){
  // do something
}

      

+2


source







All Articles