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