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