Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Xóa tất cả khoảng trắng trong chuỗi - JavaScript


Viết hàm nhận vào chuỗi, trả về chuỗi mới không chứa khoảng trắng.

Ví dụ

Mã thực hiện:

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));

Kết quả

Kết quả sau khi xóa khoảng trắng:

Thisisanexamplestringfromwhichallwhitespaceswillberemoved