Bu örnekte, bir dizenin belirli karakterlerle başlayıp bitmediğini kontrol etmek için bir JavaScript programı yazmayı öğreneceksiniz.
Bu örneği anlamak için, aşağıdaki JavaScript programlama konuları hakkında bilgi sahibi olmalısınız:
- JavaScript Dizesi
- Javascript String startsWith ()
- Javascript String pointsWith ()
- JavaScript Regex
Örnek 1: Yerleşik Yöntemleri Kullanarak Dizeyi Kontrol Etme
// 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);
Çıktı
Bir dize girin: Dize Dize S ile başlar ancak G ile bitmez
Yukarıdaki programda iki yöntem startsWith()
ve endsWith()
kullanılmaktadır.
startsWith()
Yöntem kontrolleri dize belirli dize ile başlıyorsa.endsWith()
Yöntem kontrolleri belirli dize ile dize biter eğer.
Yukarıdaki program küçük harf olup olmadığını kontrol etmez. Dolayısıyla burada G ve g farklıdır.
Ayrıca yukarıdaki karakterin S veya s ile başlayıp G veya g ile bitip bitmediğini de kontrol edebilirsiniz .
str.startsWith('S') || str.startsWith('s') && str.endsWith('G') || str.endsWith('g');
Örnek 2: Regex Kullanarak Dizeyi Kontrol Edin
// 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); )
Çıktı
Bir dize girin: Dize Dize S ile başlar ve G ile biter Bir dize girin: dize Dize S ile başlar ve G ile biter Bir dizi girin: JavaScript Dize S ile başlamaz ve G ile bitmez
Yukarıdaki programda, test()
dizenin S ile başlayıp G ile bitip bitmediğini kontrol etmek için yöntemle birlikte bir düzenli ifade (RegEx) kullanılır .
/^S/i
Desen kontrolleri dize ise S veya s . Burada,i
dizenin büyük / küçük harfe duyarlı olmadığını gösterir. Bu nedenle, S ve s aynı kabul edilir./G$/i
Desen kontrol dizisi ise G veya g .if… else… if
Deyim koşullarını kontrol ve buna göre sonuç görüntülemek için kullanılır.for
Döngü farklı durumları göstermek için kullanıcıdan farklı girişler almak için kullanılır.