如何用 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

更新於: 07-9月-2020

680 瀏覽

開啟您的 職業生涯

完成課程後獲得認證

立即開始
廣告