跳到主要内容

JavaScript 程序:从文本中移除所有空白

要理解这个示例,你应该掌握以下 JavaScript 编程 主题的知识:

示例 1:使用 split() 和 join()

// 程序用于修剪字符串

const string = " Hello World ";

const result = string.split(" ").join("");

console.log(result);

输出

HelloWorld

在上述程序中,

  • 使用 split(' ') 方法将字符串分割成单独的数组元素。
["", "", "", "", "", "", "Hello", "World", "", "", "", "", "", "", ""];
  • 使用 join('') 方法将数组合并成一个字符串。

示例 2:使用正则表达式

// 程序用于修剪字符串

function trimString(x) {
const result = x.replace(/\s/g, "");
return result;
}

const result = trimString(" Hello World ");
console.log(result);

输出

HelloWorld

在上述程序中,使用正则表达式结合 replace() 方法来去除文本中的所有空白字符。

/\s/g 用于检查字符串中的空白字符。