JavaScript 删除文本中所有空格的程序

要理解此示例,您应了解以下 JavaScript 编程 主题


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

// program to trim a string

const string = '      Hello World       ';

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

console.log(result);

输出

HelloWorld

在上面的程序中,

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

示例 2:使用正则表达式

// program to trim a string

function trimString(x) {

    const result = x.replace(/\s/g,'');
    return result

}

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

输出

HelloWorld

在上面的程序中,使用正则表达式和 replace() 方法来删除文本中的所有空格。

/\s/g 检查字符串中的空格。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战