示例 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: '); checkString(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 const 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
循环用于从用户获取不同的输入以显示不同的情况。