0

我有一个 javascript 函数,它应该用传递给函数的字母开头的数组中的所有项目填充一个选择框。我唯一的问题是我无法让我的正则表达式语句/编码工作。这是我的功能:

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

    }

}

}

有任何想法吗?

4

4 回答 4

1

这也有效,并且没有 RegEx:

if (companies[i].charAt(0).toLowerCase() == letter.toLowerCase()) {...}
于 2012-05-09T13:43:03.030 回答
0

我不会打扰正则表达式。你只会制造问题。像这样的东西会起作用。

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
于 2012-05-09T13:50:51.137 回答
0

就像是?

function foo (letter) {
 var companies  = ["microsoft","apple","google"];
  return companies.filter(function(s) { return s.match(new RegExp(letter,"ig")); });
}

alert(foo("G")); //google
于 2012-05-10T15:03:30.203 回答
0

这实际上可能在没有正则表达式的情况下更有效(当然,这将被视为微优化......)。我只会做类似的事情:

if (letter && companies[i][0].toLowerCase() === letter.toLowerCase()) { ... }
于 2012-05-09T13:42:52.790 回答