JavaScript 程序:检查字符串是否以特定字符开头和结尾

要理解此示例,您应了解以下 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: ');
checkString(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
    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 模式检查字符串是否为 Ss。这里的 i 表示字符串不区分大小写。因此,Ss 被视为相同。
  • /G$/i 模式检查字符串是否为 Gg
  • 使用 if...else...if 语句检查条件并相应显示结果。
  • 使用 for 循环从用户那里获取不同的输入,以显示不同的情况。

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战