如何用 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP