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

Loại bỏ khoảng trắng khỏi chuỗi trong JavaScript

Loại bỏ khoảng trắng khỏi chuỗi trong JavaScript

Chúng ta cần viết một hàm JavaScript nhận vào một chuỗi và trả về chuỗi mới với tất cả các ký tự của chuỗi gốc nhưng đã loại bỏ khoảng trắng.

Ví dụ

Mã thực hiện như sau:

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

Đầu ra

Kết quả trong console:

Thisisanexamplestringfromwhichallwhitespaceswillberemoved