示例1:使用内置方法检查字符串
// program to check if a string starts with 'S' and ends with 'G'
function checkString(str) {
// check if the string starts with S and ends with G
if(str.startsWith('S') && str.endsWith('G')) {
console.log('The string starts with S and ends with G');
}
else if(str.startsWith('S')) {
console.log('The string starts with S but does not end with G');
}
else if(str.endsWith('G')) {
console.log('The string starts does not with S but end with G');
}
else {
console.log('The string does not start with S and does not end with G');
}
}
// take input
let string = prompt('Enter a string: ');
}
输出
Enter a string: String
The string starts with S but does not end with G
在以上程序中,使用了startsWith()
和endsWith()
这两种方法。
- 所述
startsWith()
方法检查字符串开头与所述特定字符串。 -
endsWith()
方法检查字符串是否以特定的字符串。
上面的程序不检查小写字母。因此,这里G和g不同。
您还可以检查上述字符是否以S或s开头并以G或g结尾。
str.startsWith('S') || str.startsWith('s') && str.endsWith('G') || str.endsWith('g');
示例2:使用正则表达式检查字符串
// program to check if a string starts with 'S' and ends with 'G'
function checkString(str) {
// check if the string starts with S and ends with G
if( /^S/i.test(str) && /G$/i.test(str)) {
console.log('The string starts with S and ends with G');
}
else if(/^S/i.test(str)) {
console.log('The string starts with S but does not ends with G');
}
else if(/G$/i.test(str)) {
console.log('The string starts does not with S but ends with G');
}
else {
console.log('The string does not start with S and does not end with G');
}
}
// for loop to show different scenario
for (let i = 0; i < 3; i++) {
// take input
let string = prompt('Enter a string: ');
checkString(string);
}
输出
Enter a string: String
The string starts with S and ends with G
Enter a string: string
The string starts with S and ends with G
Enter a string: JavaScript
The string does not start with S and does not end with G
在上述程序中,正则表达式(RegEx)与test()
方法一起使用,以检查字符串是否以S开头并以G结尾。
-
/^S/i
模式检查字符串是S还是s 。在此,i
表示字符串不区分大小写。因此, S和s被认为是相同的。 -
/G$/i
模式检查字符串是G还是g 。 -
if...else...if
语句用于检查条件并相应显示结果。 -
for
循环用于从用户处获取不同的输入以显示不同的情况。