文字列に部分文字列が含まれているかどうかを確認するJavaScriptプログラム

Javascript

例1:includes()を使用して文字列をチェックする

// program to check if a string contains a substring

// take input
const str = prompt('Enter a string:');
const checkString = prompt('Enter a string that you want to check:');

// check if string contains a substring
if(str.includes(checkString)) {
    console.log(`The string contains ${checkString}`);
} else {
    console.log(`The string does not contain ${checkString}`);
}

出力

Enter a string: JavaScript is fun
Enter a string that you want to check: fun
The string contains fun

ザ・ includes() メソッドはで使用されます if...else 文字列に指定された文字列の文字が含まれているかどうかを確認するステートメント。

注意includes() メソッドでは大文字と小文字が区別されます。 したがって、 楽しい そして 楽しい 異なっています。


例2:indexOf()で文字列をチェックする

// program to check if a string contains a substring

// take input
const str = prompt('Enter a string:');
const checkString = prompt('Enter a string that you want to check:');

// check if string contains a substring
if(str.indexOf(checkString) !== -1) {
    console.log(`The string contains ${checkString}`);
} else {
    console.log(`The string does not contain ${checkString}`);
}

出力

Enter a string: JavaScript is fun
Enter a string that you want to check: fun
The string contains fun

上記のプログラムでは、 indexOf() メソッドはで使用されます if...else 文字列に部分文字列が含まれているかどうかを確認するステートメント。

ザ・ indexOf() メソッドは文字列を検索し、最初に出現した位置を返します。 部分文字列が見つからない場合は、 -1

注意indexOf() メソッドでは大文字と小文字が区別されます。



Hope this helps!

Source link

コメントを残す

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