0

I have an array like this in angular

app.myStringArray=
    [   'abcdefg',
        '123456',
        'qwerty'
    ];

Currently I have a common method that checks for value being in array like this

app.factory('commons', function () {


    var commons= {};

    //Checks if the current url is 
    commons.checkString= function (str) {

        if (app.myStringArray.indexOf(str) > -1) {
            return true; //current string is in list
        } else {
            return false;
        }
    }

    return commons;
}
);

This works if I send in the full string 'abcdefg' or '123456' or 'qwerty'.

How can I make it work even if I get part of the string like for eg: 'bcd' ?

2 Answers 2

3

To check if a string contains another one you can use String.indexOf() or as of ES6 String.includes().

To check if at least one item in an array matches a predicate you can use Array.some() or simply iterate over the array yourself.

ES6 solution:

function checkString(str) {    
  return myStringArray.some(s => s.includes(str));
}

ES5 solution:

function checkString2(str) {    
  return myStringArray.some(function(s) {
    return s.indexOf(str) > -1;
  });
}
Sign up to request clarification or add additional context in comments.

2 Comments

shouldn't it be str.indexOf(s) > -1 ?
@user20358 Not if you want to test if "abcdefg" (=s) contains "bcd" (=str).
1

Iterate through the array and check indexOf(str) for each string in the array. No need for Angular.

var array = ['abcdefg', '123456', 'qwerty'];

function checkString(str) {
  
  for (var i = 0; i < array.length; i++) {
    if (array[i].indexOf(str) > -1) {
      return true;  
    }
  }
  
  return false;
}

alert(checkString("bcd"));

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.