2012-05-09 3 views
0
로 시작하는 모든 이름

함수에 전달 된 문자로 시작하는 배열의 모든 항목을 선택 상자에 채워야하는 자바 스크립트 함수가 있습니다. 내가 가진 유일한 문제는 정규식 문/코딩 작업을 얻을 수 없다는 것입니다. 여기 내 기능은 다음과 같습니다.자바 스크립트 정규식

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 

    } 

} 

} 

아이디어가 있습니까?

+0

대답이 아니지만 질문 : 문자에 '정의되지 않은'값이 있어야하는 이유는 무엇입니까? –

+0

배열의 숫자가 데이터베이스에서 직접 나온 ID 번호와 일치하기 때문에 값이없는 숫자가 있습니다. –

+1

'typeof letter =='undefined''를 의미하지는 않습니까? 왜 두 번 proove합니까? '(문자! = '정의되지 않음'|| 문자! = '정의되지 않음')' –

답변

1

이 작동하고, 정규식없이 : 난 그냥 뭔가를 할 것이라고 내가 정규식 신경 쓰지 것

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

정규 표현식을 사용하지 않는 것이 실제로 실제로 더 효과적 일 수 있습니다 (부여되었지만 이는 미세 최적화로 간주됩니다 ...). 도

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

'회사 [i] .charAt (0)'을 원할 수도 있습니다. –

+0

'.charAt (0)'이 작동하지만, 배열 접근 자 구문을 사용하여 문자에 액세스 할 수도 있습니다 (단축형). – jmar777

+0

아 맞아. 나는 그것을 알고 있었다 ... :) –

0

. 문제가 생길뿐입니다. 이 같은 것이 효과가 있습니다.

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