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>
indexOf(someStr. toLowerCase()); That will do a case insensitive indexOf() .
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With