Чтобы сопоставить первую букву слова с последней буквой с помощью регулярных выражений в JavaScript, вы можете использовать следующие методы:
Метод 1: использование регулярного выражения
const str = "example";
const regex = /^(\w).*\1$/;
const matches = str.match(regex);
if (matches) {
const matchedString = matches[0];
console.log(`First and last letters match: ${matchedString}`);
} else {
console.log("First and last letters do not match.");
}
Метод 2: сравнение первого и последнего символов
const str = "example";
const firstLetter = str.charAt(0);
const lastLetter = str.charAt(str.length - 1);
if (firstLetter === lastLetter) {
console.log("First and last letters match.");
} else {
console.log("First and last letters do not match.");
}
Метод 3: использование подстроки
const str = "example";
const firstLetter = str.substring(0, 1);
const lastLetter = str.substring(str.length - 1);
if (firstLetter === lastLetter) {
console.log("First and last letters match.");
} else {
console.log("First and last letters do not match.");
}
Метод 4. Использование индексации массива
const str = "example";
const firstLetter = str[0];
const lastLetter = str[str.length - 1];
if (firstLetter === lastLetter) {
console.log("First and last letters match.");
} else {
console.log("First and last letters do not match.");
}