如何用 JavaScript 刪除字串中的多餘空格?
要刪除多餘空格,你需要使用 trim() 以及正則表示式。以下是如何在應用 trim() 之前使用含有空格的字串 −
var sentence="My name is John Smith ";
現在,我們將移除多餘空格,程式碼如下 −
示例
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.
此處,我的檔名是 demo90.js。
輸出
由此產生的輸出如下 −
PS C:\Users\Amit\JavaScript-code> node demo90.js The actual value= My name is John Smith After removing the spaces= MynameisJohnSmith
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP