Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ลบช่องว่างทั้งหมดออกจากสตริง - JavaScript

ลบช่องว่าง (whitespace) ทั้งหมดออกจากสตริง คืนค่าสตริงต่อเนื่อง

ตัวอย่างโค้ด

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];
  }
  return newStr;
};

console.log(removeWhitespaces(str));

ผลลัพธ์

Thisisanexamplestringfromwhichallwhitespaceswillberemoved

วิธีแบบ Built-in (แนะนำ)

// ลบเฉพาะ space
const removeSpaces = str => str.replace(/ /g, '');

// ลบ whitespace ทุกชนิด (space, tab, newline, etc.)
const removeAllWhitespace = str => str.replace(/\s/g, '');

// หรือใช้ split + join
const removeSpaces = str => str.split(' ').join('');

/\s/g จับ whitespace ทุกประเภท: space, tab (\t), newline (\n), carriage return (\r), form feed (\f)