ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงและแทนที่จุด (.) ทั้งหมดด้วยขีด (-)
Input
const str = 'this.is.an.example.string';
Output
const output = 'this-is-an-example-string';
จุดทั้งหมดในสตริง str ถูกแทนที่ด้วยขีด
ตัวอย่าง
โค้ดด้านล่างนี้
const str = 'this.is.an.example.string';
const replaceDots = (str = '') => {
let res = "";
const { length: len } = str;
for (let i = 0; i < len; i++) {
const el = str[i];
if(el === '.'){
res += '-';
}else{
res += el;
}
}
return res;
};
console.log(replaceDots(str));คำอธิบายโค้ด
เราวนลูปผ่านสตริง str และถ้าตัวอักษรปัจจุบันเป็นจุด ให้เพิ่มขีดใน res ไม่เช่นนั้นเพิ่มตัวอักษรปัจจุบัน
ผลลัพธ์
this-is-an-example-string