如何使用 JavaScript 中的 replace() 從字串中去除空格?


假設以下是用空格串聯的字串 −

var fullName=" John Smith ";

使用 replace() 並在其中設定 Regex 以去除空格。

示例

function removeSpacesAtTheBeginningAndTheEnd(name) {
   return name.toString().replace(/^\s+|\s+$/g,'');
}
var fullName=" John Smith ";
var
valueAfterRemovingSpace=removeSpacesAtTheBeginningAndTheEnd(fullName)
console.log(valueAfterRemovingSpace);

要執行以上程式,您需要使用以下命令 −

node fileName.js.

此處我的檔名是 demo208.js。

輸出

這將產生以下輸出 −

PS C:\Users\Amit\javascript-code> node demo208.js
John Smith

更新於: 01-Sep-2020

147 次瀏覽

開啟 職業生涯

完成課程獲取認證

立即開始
廣告
© . All rights reserved.