2016-09-29 66 views
1

我試着運行此代碼,但它不起作用,有人可以幫忙嗎?如果語句比較姓氏是否以字母開頭A-L

var lastName = document.queryselector('lastName'); 
var message = document.queryselector('message'); 

function checkFirstLetterOfLastName() { 
if (/^[A-L]/.test(lastName)) { 
message.textContent = 'Go stand in first line'; 
} else { 
message.textContent = 'Go stand in first line'; 
} 
} 

checkFirstLetterOfLastName(); 
+0

這是不明確的,在所有的,什麼是'A-L'應該是什麼? – adeneo

+0

@ adeneo A到L的一封信。不知道爲什麼他們認爲即使是短暫的也可能工作。 – jonrsharpe

+0

至少,您應該追求有效的語法;我會推薦一些類型的教程。 – jonrsharpe

回答

2

function checkFirstLetterOfLastName(lastname) { 
 
    if((/^[A-L].+/i).test(lastname)) { 
 
    console.log('starts with A-L'); 
 
    } 
 
    else 
 
    { 
 
    console.log('does not starts with A-L'); 
 
    } 
 
} 
 

 
checkFirstLetterOfLastName("hello")

+0

Isn 't'。+'多餘的? –

4

這裏是一個工作示例使用正則表達式:

function checkFirstLetterOfLastName(lastName) { 
 
    if (/^[A-L]/.test(lastName)) { 
 
    console.log(lastName, 'starts with A-L'); 
 
    } else { 
 
    console.log(lastName, 'does not start with A-L'); 
 
    } 
 
} 
 

 
checkFirstLetterOfLastName('Carlson'); 
 
checkFirstLetterOfLastName('Mathews');

0

foo('Avery'); 
 
foo('David'); 
 
foo('Laura'); 
 
foo('Michael'); 
 
foo('Zachary'); 
 

 
function foo(x) { 
 
    if(x.match(/^[A-L]/i)) { 
 
    console.log('Go stand in first line.') 
 
    } 
 
    else console.log('Go stand in second line.'); 
 
}

這是否適合您?

0

我會用正則表達式,這和使用expression.test方法它像這樣:

// a string that starts with a letter between A and L 
var str = 'Hello!' 
// a string that does not start with a letter between A and L 
var notPass = 'SHould not pass' 
// Note: this only checks for capital letters 
var expr = /[A-L]/ 
console.log(expr.test(str[0])) 
console.log(expr.test(notPass[0])) 
相關問題