Gynteniuxas
Gynteniuxas

Reputation: 7093

Javascript: multiple expressions in array when searching strings

I'm currently working with Javascript and for now I'm searching a way to check if variable contains at least one string. I have looked at previous questions, however, neither contain what I'm 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
}

Variable a is user's written text (for example, a comment or a post).

I want to check if user has written certain word in it and return an alert message to remove/edit that word. While my written function works, it only works when user writes that word exactly as I write in my variable ("Three" != "three"). I want to improve my funtion so it would also find case-insensitive ("Three" == "three") and part of words (like "thr" from "three"). I tried to put an expression like * but it didn't work.

It would be the best if every expression could be written in one function. Otherwise, I might need help with combining two functions.

Upvotes: 3

Views: 122

Answers (2)

Barmar
Barmar

Reputation: 781058

Use indexOf to test 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;
    }

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

You can use Array.some with Object.keys

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

Upvotes: 0

Related Questions