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

输入:

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

输出:

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

当前回答

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

有两种方法!

其他回答

正则表达式+ Replace()

虽然regex可能更慢,但在很多情况下,开发人员一次只操作几个字符串,所以考虑速度是无关紧要的。尽管/ /比/\s/快,但是使用'\s'可能更清楚地向其他开发人员解释了正在发生的事情。

let string = '/var/www/site/Brand new document.docx';
let path = string.replace(/\s/g, '');
// path => '/var/www/site/Brandnewdocument.docx'

Split() + Join()

使用Split + Join可以对字符串进行进一步的链式操作。

let string = '/var/www/site/Brand new document.docx';
let path => string.split('').map(char => /(\s|\.)/.test(char) ? '/' : char).join('');
// "/var/www/site/Brand/new/document/docx";

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

有两种方法!

你还可以使用JS中最新的字符串方法之一:replaceAll

'/var/www/site/Brand new document.docx'.replaceAll(' ', '');
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);

输出:

你好世界

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

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