У цьому прикладі ви навчитеся писати програму JavaScript, щоб перевірити, чи рядок починається та закінчується певними символами.
Щоб зрозуміти цей приклад, ви повинні знати такі теми програмування JavaScript:
- Рядок JavaScript
- Рядок Javascript починається з ()
- Рядок Javascript закінчується з ()
- Регулярний вираз JavaScript
Приклад 1: Перевірте рядок за допомогою вбудованих методів
// 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);
Вихідні дані
Введіть рядок: Рядок Рядок починається з S, але не закінчується G
У наведеній вище програмі, ці два методи startsWith()
і endsWith()
використовуються.
- У
startsWith()
методі перевірки , якщо рядок починається з певної рядком. - У
endsWith()
метод перевірки , якщо рядок закінчується з певною рядком.
Вищевказана програма не перевіряє наявність малих літер. Отже, тут G і g різні.
Ви також можете перевірити, чи наведений вище символ починається з S або s і закінчується G або g .
str.startsWith('S') || str.startsWith('s') && str.endsWith('G') || str.endsWith('g');
Приклад 2: Перевірте рядок за допомогою регулярного виразу
// 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); )
Вихідні дані
Введіть рядок: String Рядок починається з S і закінчується G Введіть рядок: string Рядок починається з S і закінчується G Введіть рядок: JavaScript Рядок не починається з S і не закінчується G
У наведеній вище програмі, регулярний вираз (RegEx) використовується з test()
методом , щоб перевірити , якщо рядок починається з S і закінчується з G .
- У
/^S/i
моделі перевірки , якщо рядок S або s . Тутi
позначає, що рядок не враховує регістр. Отже, S і s вважаються однаковими. - Ці
/G$/i
шаблони перевіряє , є чи рядок G або г . if… else… if
Оператор використовується для перевірки умов і відображення результату відповідно.for
Цикл використовується для приймати різні вхідні сигнали від користувача , щоб показати різні випадки.