📌  相关文章
📜  JavaScript程序,用于检查字符串是否以某些字符开头和结尾

📅  最后修改于: 2020-09-27 05:33:32             🧑  作者: Mango

在此示例中,您将学习编写JavaScript程序来检查字符串是否以某些字符开头和结尾。

示例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()方法检查字符串是否以特定的字符串。

上面的程序不检查小写字母。因此,这里Gg不同。

您还可以检查上述字符是否以Ss开头并以Gg结尾。

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表示字符串不区分大小写。因此, Ss被认为是相同的。
  • /G$/i模式检查字符串是G还是g
  • if...else...if语句用于检查条件并相应显示结果。
  • for循环用于从用户处获取不同的输入以显示不同的情况。