3

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.

3

2 Answers 2

1

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Array.some with Object.keys

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

3 Comments

You need to compare indexOf with -1. How does ~~ turn it into a boolean?
I intended to use ~
Why add * to the key when creating the regexp? That means the last character of the key can appear zero or more times. So it will match if the last character is missing.

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.