เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงและส่งคืนสตริงใหม่โดยลบอักขระทั้งหมดของสตริงเดิมออกเพียงช่องว่าง
ตัวอย่าง
มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −
const str = "This is an example string from which all whitespaces will be
removed";
const removeWhitespaces = str => {
let newStr = '';
for(let i = 0; i < str.length; i++){
if(str[i] !== " "){
newStr += str[i];
}else{
newStr += '';
};
};
return newStr;
};
console.log(removeWhitespaces(str)); ผลลัพธ์
ผลลัพธ์ในคอนโซลหลังจากลบช่องว่าง -
Thisisanexamplestringfromwhichallwhitespaceswillberemoved