文字列が特定の文字で開始および終了するかどうかを確認する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

上記のプログラムでは、2つの方法 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 ループは、ユーザーからさまざまな入力を受け取り、さまざまなケースを表示するために使用されます。



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です