2016-09-29 73 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])) 
相关问题