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

ลบช่องว่างเกินในสตริงด้วย JavaScript

ใช้ replace() กับ Regex /\s+/g แทนช่องว่างหลายช่องเป็นช่องเดียว แล้ว trim() ตัดช่องว่างปลาย

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

var sentence = "My name is John Smith ";
console.log("The actual value=");
console.log(sentence);

var originalSentence = sentence.replace(/\s+/g, ' ').trim();
var afterRemovingTheSpace = originalSentence.trim();

console.log("After removing the spaces=");
console.log(afterRemovingTheSpace);

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo90.js)

ผลลัพธ์

The actual value= My name is John Smith 
After removing the spaces= My name is John Smith

หมายเหตุ: โค้ดต้นฉบับมี bug ใช้ replace(/\s+/g, '') จะลบช่องว่างหมด ใช้ ' ' แทน '' จะเก็บช่องว่างระหว่างคำไว้