เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงเข้ามา ซึ่งอาจมีเครื่องหมายคำถาม (?) อยู่ที่ ต้นและท้ายของสตริง ฟังก์ชันควรตัดเครื่องหมายเหล่านี้ออก โดยคงส่วนกลางไว้เหมือนเดิม
ตัวอย่าง
const str = '??this is a ? string?';
ผลลัพธ์ที่คาดหวัง:
'this is a ? string'
โค้ดตัวอย่าง (วิธีเดิม - ซับซ้อน)
const str = '??this is a ? string?';
const specialTrim = (str = '', char = '?') => {
str = str.trim();
let countChars = orientation => {
let inner = (orientation == "left") ? str :
str.split("").reverse().join("");
let count = 0;
for (let i = 0, len = inner.length; i < len; i++) {
if (inner[i] !== char) break;
count++;
}
return (orientation == "left") ? count : (-count);
};
const condition = typeof char === 'string' &&
str.indexOf(char) === 0 &&
str.lastIndexOf(char, -1) === 0;
if (condition) {
str = str.slice(countChars("left"), countChars("right")).trim();
}
return str;
};
console.log(specialTrim(str));
วิธีที่ง่ายและทันสมัยกว่า
// ใช้ trim() กับชุดตัวอักษรที่ต้องการตัด
const simpleTrim = (str, char = '?') => {
// สร้าง regex pattern สำหรับตัดต้นและท้าย
const escapedChar = char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(`^[${escapedChar}]+|[${escapedChar}]+$`, 'g');
return str.replace(regex, '');
};
// หรือใช้ trim() พร้อมระบุตัวอักษร (ES2019+)
const modernTrim = (str, char = '?') => str.trimStart(char).trimEnd(char);
console.log(simpleTrim('??this is a ? string?')); // 'this is a ? string'
console.log(modernTrim('??this is a ? string?')); // 'this is a ? string'
ผลลัพธ์
this is a ? string
สรุป
String.prototype.trimStart()และtrimEnd()รองรับการระบุตัวอักษรที่ต้องการตัด (ES2019)- Regex ให้ความยืดหยุ่นสูงสุดและทำงานได้ในทุกสภาพแวดล้อม
- โค้ดต้นฉบับซับซ้อนเกินความจำเป็น