Computer >> Máy Tính >  >> Lập trình >> Javascript

Cách xóa tất cả khoảng trắng trong chuỗi bằng JavaScript

Để loại bỏ tất cả các khoảng trắng trong một chuỗi bằng JavaScript, bạn có thể sử dụng RegEx:

const sentence = "This sentence has 6 white space characters."

console.log(sentence.replace(/\s/g, ""))
// "Thissentencehas6whitespacecharacters."

Ví dụ trên chỉ đăng xuất kết quả, nó không lưu các thay đổi.

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

// Sentence with whitespaces
const sentence = "This sentence has 6 white space characters."

// Sentence without whitespace
const sentenceRemoveWhiteSpace = sentence.replace(/\s/g, "")

console.log(sentenceRemoveWhiteSpace)
// Thissentencehas6whitespacecharacters.