1

I want to check if a string like "me and her" contains a value from an array. The array could look like:

[" and ", "Mr", "sir"]

If it does it should return false. That means that "John Doe" should return true but "Mr. John Doe" or "john and Jane Doe" should return false

I don't think I can use $.inArray as it only checks for the specific value and not part of the string.

Anyone?

1
  • why should Mr. John Doe return false? None of the words are exact matches of those in the array Commented Aug 11, 2016 at 14:52

2 Answers 2

1

You can use the native JavaScript String.includes() method to check if a string includes a value, then loop through your list of things. Something like this:

function checkStringAgainstList(str) {
    var exclude = ['Mr', 'and', 'Mrs'];
    for (var ndx in exclude) {
        if(str.includes(exclude[ndx])) {
            return false;
        }
    }
    return true;
}

This seems like what you want. Here's a fiddle

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

1 Comment

This is exactly what I was looking for, Nice solution
1

This should be the kind of thing you are looking for:

var myArray = ["Mr", "and", "Sir"];

function checkForString(inputString) {
  var runningTotal = 0;
  //For loop to check each item of the array against the string, to see if it appears
  for (var i = 0; i < myArray.length; i++) {
      runningTotal += inputString.toLowerCase().indexOf(myArray[i].toLowerCase());
  }
  //Check the running total. Each term that DOESN'T appear in the string, returns -1, so multiply by the array length to find the value if none of the items in the array appear in the string
  if (runningTotal == (myArray.length * -1)) {
    return true;
    } else {
    return false;  
      }
  }
console.log('Mr John Doe = ' + checkForString("Mr John Doe"))
console.log('John Doe = ' + checkForString("John Doe"));

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.