如何使用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP