Contoh 1: Periksa String Menggunakan Metode Bawaan
// 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);
Keluaran
Enter a string: String The string starts with S but does not end with G
Dalam program di atas, dua metode startsWith()
dan endsWith()
digunakan.
- Itu
startsWith()
metode memeriksa apakah string dimulai dengan string tertentu. - Itu
endsWith()
metode memeriksa apakah string diakhiri dengan string tertentu.
Program di atas tidak memeriksa huruf kecil. Oleh karena itu, di sini G dan g berbeda.
Anda juga dapat memeriksa apakah karakter di atas dimulai dengan S atau s dan diakhiri dengan G atau g.
str.startsWith('S') || str.startsWith('s') && str.endsWith('G') || str.endsWith('g');
Contoh 2: Periksa String Menggunakan Regex
// 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);
}
Keluaran
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
Dalam program di atas, ekspresi reguler (RegEx) digunakan dengan test()
metode untuk memeriksa apakah string dimulai dengan S dan diakhiri dengan G.
- Itu
/^S/i
pola memeriksa apakah string itu S atau s. Sini,i
menunjukkan bahwa string tidak peka huruf besar / kecil. Karenanya, S dan s dianggap sama. - Itu
/G$/i
pola memeriksa apakah string itu G atau g. - Itu
if...else...if
pernyataan digunakan untuk memeriksa kondisi dan menampilkan hasilnya sesuai. - Itu
for
loop digunakan untuk mengambil input yang berbeda dari pengguna untuk menunjukkan kasus yang berbeda.