删除 JavaScript 字符串中的多余空格?

javascriptweb developmentobject oriented programming更新于 2025/11/11 8:12:17

要删除多余空格,您需要使用 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

相关文章


有用资源