Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make Array.indexOf() case insensitive?

Tags:

javascript

I am making a piece of code for a website that will have a list of names in an array and pick a random name, I want to add a feature that will let the user add or delete a name from the array. I have all of these features but when deleting a name, the user has to type the name to match the Case in the array. I tried to make the so it would be Case-Insensitive, what am I doing wrong?

<html> <!--Other code uneeded for this question--> <p id="canidates"></p> <body> <input type="text" id="delname" /><button onclick="delName()">Remove Name from List</button> <script>  //Array of names  var names = [];  //Other code uneeded for this question  //List of Canidates document.getElementById('canidates').innerHTML =  "<strong>List of Canidates:</strong> " + names.join(" | ");  //Other code uneeded for this question  //Remove name from Array  function delName() {     var dnameVal = document.getElementById('delname').value;     var pos = names.indexOf(dnameVal);     var namepos = names[pos]     var posstr = namepos.toUpperCase();     var dup = dnameVal.toUpperCase();     if(dup != posstr) {         alert("Not a valid name");         }     else {         names.splice(pos, 1);         document.getElementById('canidates').innerHTML =          "<strong>List of Canidates:</strong> " + names.join(" | ");         }     }    </script> </body> </html> 
like image 894
Malcolm Avatar asked Jul 12 '14 23:07

Malcolm


People also ask

How do I make indexOf not case sensitive?

indexOf(someStr. toLowerCase()); That will do a case insensitive indexOf() .

Is array indexOf case sensitive?

We can't get the index of an element by performing a case insensitive lookup with Array. indexOf , because the method takes in the value directly and does not allow us to iterate over each array element and manipulate them (e.g. lowercase).

Can you do indexOf for an array?

Introduction to the JavaScript array indexOf() methodTo find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.


1 Answers

ES2015 findIndex:

var array = ['I', 'hAve', 'theSe', 'ITEMs'],     indexOf = (arr, q) => arr.findIndex(item => q.toLowerCase() === item.toLowerCase());  console.log(  indexOf(array, 'i')      ) // 0 console.log(  indexOf(array, 'these')  ) // 2 console.log(  indexOf(array, 'items')  ) // 3
like image 149
vsync Avatar answered Sep 29 '22 18:09

vsync