ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงและแทนที่การปรากฏของจุด (.) ทั้งหมดในนั้นด้วยขีดกลาง (-)
อินพุต
const str = 'this.is.an.example.string';
ผลผลิต
const output = 'this-is-an-example-string';
การปรากฏทั้งหมดของ dot(.) ในสตริง str จะถูกแทนที่ด้วย dash(-)
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
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