如何删除字符串中的空格?例如:

输入:

'/var/www/site/Brand new document.docx'

输出:

'/var/www/site/Brandnewdocument.docx'

当前回答

使用replaceAll似乎是最简单、最干净的方法。(我不能保证最快)

“/var/www/site/Brand new document.docx”。替代品(',')

见文档。

replaceAll()方法返回一个新字符串,其中模式的所有匹配项都被替换。模式可以是字符串或RegExp,替换可以是为每个匹配调用的字符串或函数。

其他回答

var a = b = " /var/www/site/Brand new document.docx "; Console.log (a.split(' ').join(")); Console.log (b.replace(/\s/g, "));

有两种方法!

这个吗?

str = str.replace(/\s/g, '');

例子

var str = '/var/www/site/Brand new document.docx'; document.write( str.replace(/\s/g, '') );


更新:基于这个问题,如下:

str = str.replace(/\s+/g, '');

是更好的解决方案。它产生相同的结果,但速度更快。

正则表达式

\s是“空白”的正则表达式,g是“全局”标志,意思是匹配所有(空白)。

关于+的一个很好的解释可以在这里找到。

作为旁注,您可以将单引号之间的内容替换为您想要的任何内容,因此您可以将空白替换为任何其他字符串。

从字符串中删除空格最简单的方法是使用replace

let str = '/var/www/site/Brand new document.docx';
let result = str.replace(/\s/g, '');

var str='/var/www/site/全新文档.docx'; document。写入(str.replace(/\ s/g,"); ----------

your_string = 'Hello world';
words_array = your_tring.split(' ');

string_without_space = '';

for(i=0; i<words_array.length; i++){
    new_text += words_array[i]; 
}

console.log("The new word:" new_text);

输出:

你好世界