Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string inside an array javascript

Tags:

javascript

If i had an array of days names and i wanted to check for example if sunday - first letter capital or small - in this array what would be the best thing to do ?

like image 900
Yasser Moussa Avatar asked Jan 22 '13 14:01

Yasser Moussa


2 Answers

You may also use Array.indexOf:

var days = ["monday",
            "tuesday",
            "wednesday",
            "thursday",
            "friday",
            "saturday",
            "sunday"];

function isInArray(days, day) {
    return days.indexOf(day.toLowerCase()) > -1;
}

isInArray(days, "Sunday");  // true
isInArray(days, "sunday");  // true
isInArray(days, "sUnDaY");  // true
isInArray(days, "Anyday");  // false

Check the browser compatibility in MDN.

like image 107
VisioN Avatar answered Oct 05 '22 14:10

VisioN


function is_in_array(s,your_array) {
    for (var i = 0; i < your_array.length; i++) {
        if (your_array[i].toLowerCase() === s.toLowerCase()) return true;
    }
    return false;
}

Usage:

var arr = ["hello","ToTo"];
is_in_array("toto",arr) //true
is_in_array("todto",arr) //false
like image 36
JohnJohnGa Avatar answered Oct 05 '22 13:10

JohnJohnGa