ภาพรวม
บทความนี้แสดงวิธีเขียนฟังก์ชันที่รับสตริง แล้วกลับลำดับตัวอักษรของคำที่มีความยาวเป็นเลขคู่ (Even Length) เท่านั้น
ตัวอย่าง
const str = 'This is an example string';
// คำที่มีความยาวคู่: This(4), is(2), an(2), string(6)
// คำที่มีความยาวคี่: example(7) -> ไม่กลับ
การนำไปใช้
const str = 'This is an example string';
const isEven = (str) => str.length % 2 === 0;
const reverseEvenWords = (str = '') => {
return str.split(' ').reduce((acc, val) => {
if (isEven(val)) {
acc.push(val.split('').reverse().join(''));
} else {
acc.push(val);
}
return acc;
}, []).join(' ');
};
console.log(reverseEvenWords(str));
ผลลัพธ์
sihT si na example gnirts
วิธีการทันสมัย (ES6+)
// ใช้ map แทน reduce (อ่านง่ายกว่า)
const reverseEvenWordsMap = (str) =>
str.split(' ')
.map(word => word.length % 2 === 0 ? [...word].reverse().join('') : word)
.join(' ');
// ใช้ regex แยกคำ (รองรับ punctuation ดีกว่า)
const reverseEvenWordsRegex = (str) =>
str.replace(/\b\w+\b/g, word =>
word.length % 2 === 0 ? [...word].reverse().join('') : word
);
การประยุกต์ใช้
- Text Obfuscation (การทำให้ข้อความอ่านยาก)
- Word Games / Puzzles
- Text Processing Pipeline
ข้อควรพิจารณา
- การจัดการ Punctuation: คำว่า "hello," ความยาว 6 (รวม comma) หรือ 5?
- Unicode: อักขระไทย/อิโมจิ อาจนับความยาวต่างจากที่คาดหวัง (ใช้ `[...str]` แทน `str.split('')`)
- Whitespace หลายประเภท: tab, newline, multiple spaces
เวอร์ชันจัดการ Unicode และ Punctuation
const reverseEvenWordsRobust = (str) => {
// แยกคำและ punctuation แยกกัน
return str.replace(/(\p{L}+)/gu, (word) =>
[...word].length % 2 === 0 ? [...word].reverse().join('') : word
);
};