文字列が別の文字列で始まるかどうかを確認するJavaScriptプログラム

Javascript

目次

例1:startsWith()の使用

// program to check if a string starts with another string

const string = 'hello world';

const toCheckString = 'he';

if(string.startsWith(toCheckString)) {
    console.warn('The string starts with "he".');
}
else {
    console.warn(`The string does not starts with "he".`);
}

出力

The string starts with "he".

上記のプログラムでは、 startsWith() メソッドは、文字列がで始まるかどうかを判断するために使用されます ‘彼’。 ザ・ startsWith() メソッドは、文字列が特定の文字列で始まるかどうかをチェックします。

ザ・ if...else ステートメントは、状態をチェックするために使用されます。


例2:lastIndexOf()の使用

// program to check if a string starts with another string

const string = 'hello world';

const toCheckString = 'he';

let result = string.lastIndexOf(toCheckString, 0) === 0;
if(result) {
    console.warn('The string starts with "he".');
}
else {
    console.warn(`The string does not starts with "he".`);
}

出力

The string starts with "he".

上記のプログラムでは、 lastIndexOf() メソッドは、文字列が別の文字列で始まるかどうかを確認するために使用されます。

ザ・ lastIndexOf() メソッドは、検索された文字列のインデックスを返します(ここでは最初のインデックスから検索します)。


例3:正規表現の使用

// program to check if a string starts with another string

const string = 'hello world';

const pattern = /^he/;

let result = pattern.test(string);

if(result) {
    console.warn('The string starts with "he".');
}
else {
    console.warn(`The string does not starts with "he".`);
}

出力

The string starts with "he".

上記のプログラムでは、文字列は正規表現パターンと test() 方法。

/^ 文字列の開始を示します。



Hope this helps!

Source link

コメントを残す

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