Javascript正则表达式的所有名称都以

时间:2012-05-09 13:39:11

标签: javascript regex drop-down-menu

我有一个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 个答案:

答案 0 :(得分:1)

这也有效,而且没有RegEx:

if (companies[i].charAt(0).toLowerCase() == letter.toLowerCase()) {...}

答案 1 :(得分:0)

如果没有正则表达式,这实际上可能更有效率(被授予,这将被视为微优化虽然......)。我会做类似的事情:

if (letter && companies[i][0].toLowerCase() === letter.toLowerCase()) { ... }

答案 2 :(得分: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

答案 3 :(得分: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