I have a javascript function which should populate a select box with all items from an array starting with the letter passed to the function. The only problem I have is that I can't get my regex statement/coding to work. Here is my function:
function replaceCompanySelect (letter)
{
var list = document.getElementById("company"); //Declare the select box as a variable
list.options.length=0; //Delete the existing options
list.options[0]=new Option("Please Select a Company", "0", false, false); //Add the first option in
for(var i=1;i<companies.length;i++) //For each company in the array
{
if(companies[i].match("/\b"+letter+"/g") != null && (letter != 'undefined' ||letter != 'undefined')) //If the company starts with the correct letter and the position's value is not undefined or empty
{
alert(companies[i]); //Only used for testing purposes, code should be as above loop to I used to insert the 1st option
}
}
}
Any ideas?
这也可以,并且没有RegEx也可以:
if (companies[i].charAt(0).toLowerCase() == letter.toLowerCase()) {...}
This is actually probably more efficient to do without regular expressions (granted, this would count as micro-optimization though...). I would just do something like:
if (letter && companies[i][0].toLowerCase() === letter.toLowerCase()) { ... }
I wouldn't bother with a regex. You'll just create problems. Something like this would work.
var companies = ["microsoft","apple","google"],
startsWith = function(arr,match){
var length = arr.length;
for(var i=0; i < length; i+=1){
if(arr[i].toUpperCase().lastIndexOf(match.toUpperCase(), 0) === 0){
return arr[i];
}
}
};
console.log(startsWith(companies,"g")); //=> returns google
Something like?
function foo (letter) {
var companies = ["microsoft","apple","google"];
return companies.filter(function(s) { return s.match(new RegExp(letter,"ig")); });
}
alert(foo("G")); //google
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.