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

Cách Xóa Tất Cả Khoảng Trắng Trong Chuỗi Với JavaScript

Để xóa tất cả khoảng trắng trong chuỗi với JavaScript, bạn có thể dùng RegEx:

const sentence = "This sentence has 6 white space characters." console.log(sentence.replace(/\s/g, "")) // "Thissentencehas6whitespacecharacters."

Ví dụ trên chỉ log kết quả, không lưu thay đổi.

Nếu muốn xóa vĩnh viễn khoảng trắng, tạo biến mới gán giá trị sentence.replace(/\s/g, ""):

// Chuỗi có khoảng trắng const sentence = "This sentence has 6 white space characters." // Chuỗi không khoảng trắng const sentenceRemoveWhiteSpace = sentence.replace(/\s/g, "") console.log(sentenceRemoveWhiteSpace) // Thissentencehas6whitespacecharacters.