Contoh 1: Menggunakan startWith()
// 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".`);
}
Keluaran
The string starts with "he".
Pada program di atas, startsWith()
metode yang digunakan untuk menentukan apakah string dimulai dengan ‘dia’. Itu startsWith()
metode memeriksa apakah string dimulai dengan string tertentu.
Itu if...else
pernyataan digunakan untuk memeriksa kondisi.
Contoh 2: Menggunakan 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".`);
}
Keluaran
The string starts with "he".
Pada program di atas, lastIndexOf()
metode ini digunakan untuk memeriksa apakah sebuah string dimulai dengan string lain.
Itu lastIndexOf()
metode mengembalikan indeks dari string yang dicari (di sini mencari dari indeks pertama).
Contoh 3: Menggunakan RegEx
// 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".`);
}
Keluaran
The string starts with "he".
Dalam program di atas, string diperiksa menggunakan pola RegEx dan test()
metode.
/^
menunjukkan awal string.