简体   繁体   English

如何使用 JavaScript 从字符串中删除空格?

[英]How to remove spaces from a string using JavaScript?

How to remove spaces in a string?如何去除字符串中的空格? For instance:例如:

Input:输入:

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

Output: Output:

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

This?这个?

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

Example例子

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


Update: Based on this question , this:更新:基于这个问题,这个:

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

is a better solution.是一个更好的解决方案。 It produces the same result, but it does it faster.它产生相同的结果,但速度更快。

The Regex正则表达式

\s is the regex for "whitespace", and g is the "global" flag, meaning match ALL \s (whitespaces). \s是“空白”的正则表达式, g是“全局”标志,表示匹配所有\s (空白)。

A great explanation for + can be found here . +的一个很好的解释可以在这里找到。

As a side note, you could replace the content between the single quotes to anything you want, so you can replace whitespace with any other string.作为旁注,您可以将单引号之间的内容替换为您想要的任何内容,因此您可以将空格替换为任何其他字符串。

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

Two ways of doing this!有两种方法可以做到这一点!

SHORTEST and FASTEST : str.replace(/ /g, '');最短和最快:str.replace str.replace(/ /g, '');


Benchmark:基准:

Here my results - (2018.07.13) MacOs High Sierra 10.13.3 on Chrome 67.0.3396 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):这是我的结果 - (2018.07.13) MacOs High Sierra 10.13.3 on Chrome 67.0.3396 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):

SHORT strings短字符串

Short string similar to examples from OP question类似于 OP 问题示例的短字符串

在此处输入图像描述

The fastest solution on all browsers is / /g (regexp1a) - Chrome 17.7M (operation/sec), Safari 10.1M, Firefox 8.8M.所有浏览器上最快的解决方案是/ /g (regexp1a) - Chrome 17.7M (operation/sec), Safari 10.1M, Firefox 8.8M。 The slowest for all browsers was split-join solution.所有浏览器中最慢的是split-join​​案。 Change改变 to \s or add + or i to regexp slows down processing.\s或将+i添加到正则表达式会减慢处理速度。

LONG strings长字符串

For string about ~3 milion character results are:对于大约 300 万个字符的字符串,结果是:

  • regexp1a : Safari 50.14 ops/sec, Firefox 18.57, Chrome 8.95 regexp1a :Safari 50.14 操作/秒,Firefox 18.57,Chrome 8.95
  • regexp2b : Safari 38.39, Firefox 19.45, Chrome 9.26 regexp2b :Safari 38.39、Firefox 19.45、Chrome 9.26
  • split-join : Firefox 26.41, Safari 23.10, Chrome 7.98,拆分加入:Firefox 26.41、Safari 23.10、Chrome 7.98、

You can run it on your machine: https://jsperf.com/remove-string-spaces/1你可以在你的机器上运行它: https ://jsperf.com/remove-string-spaces/1

["

Following @rsplak answer: actually, using split\/join way is faster than using regexp.<\/i>遵循@rsplak 的回答:实际上,使用拆分\/加入方式比使用正则表达式更快。<\/b> See the performance test case<\/a><\/i>查看性能测试用例<\/a><\/b><\/p>

So<\/i>所以<\/b><\/p>

var result = text.split(' ').join('')<\/code><\/p>

operates faster than<\/i>运行速度比<\/b><\/p>

var result = text.replace(\/\\s+\/g, '')<\/code><\/p>

On small texts this is not relevant, but for cases when time is important, eg in text analisers, especially when interacting with users, that is important.<\/i>对于小文本,这无关紧要,但对于时间很重要的情况,例如在文本分析器中,尤其是在与用户交互时,这很重要。<\/b><\/p>


On the other hand, \\s+<\/code> handles wider variety of space characters.<\/i>另一方面, \\s+<\/code>处理更多种类的空格字符。<\/b> Among with \\n<\/code> and \\t<\/code> , it also matches \ <\/code> character, and that is what &nbsp;<\/code><\/i>在与\\n<\/code>和\\t<\/code>中,它还匹配\ <\/code>字符,这就是&nbsp;<\/code><\/b> is turned in, when getting text using textDomNode.nodeValue<\/code> .<\/i>使用textDomNode.nodeValue<\/code>获取文本时被打开。<\/b><\/p>

So I think that conclusion in here can be made as follows: if you only need to replace spaces<\/em> ' '<\/code> , use split\/join.<\/i>所以我认为这里的结论可以如下:如果你只需要替换空格<\/em>' '<\/code> ,使用split\/join。<\/b> If there can be different symbols of symbol class<\/em> - use replace(\/\\s+\/g, '')<\/code><\/i>如果符号类<\/em>可以有不同的符号 - 使用replace(\/\\s+\/g, '')<\/code><\/b><\/p>"]

easy way简单的方法

someString.replace(/ /g, '');
// or
someString.replace(/\s/gm, '');
var input = '/var/www/site/Brand new document.docx';

//remove space
input = input.replace(/\s/g, '');

//make string lower
input = input.toLowerCase();

alert(input);

Click here for working example单击此处查看工作示例

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

'/var/www/site/Brand new document.docx'.replaceAll(' ', '');

Without regexp , it works fine.没有 regexp ,它工作正常。

input = input.replace(' ', '');

Why not use simply this !?为什么不简单地使用这个!? This is faster as simple !这更快更简单!

  var output = '/var/www/site/Brand new document.docx'.replace(/ /g, ""); 
    or
  var output = '/var/www/site/Brand new document.docx'.replace(/ /gi,"");

Note: Though you use 'g' or 'gi' for removing spaces both behaves the same.注意:尽管您使用“g”或“gi”来删除空格,但两者的行为相同。

If we use 'g' in the replace function, it will check for the exact match.如果我们在替换函数中使用“g”,它将检查是否完全匹配。 but if we use 'gi', it ignores the case sensitivity.但是如果我们使用'gi',它会忽略大小写敏感。

for reference click here .参考点击这里

Regex + Replace()正则表达式 + 替换()

Although regex can be slower, in many use cases the developer is only manipulating a few strings at once so considering speed is irrelevant.尽管正则表达式可能会更慢,但在许多用例中,开发人员一次只操作几个字符串,因此考虑速度是无关紧要的。 Even though / / is faster than /\s/, having the '\s' explains what is going on to another developer perhaps more clearly.尽管 / / 比 /\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()拆分()+加入()

Using Split + Join allows for further chained manipulation of the string.使用 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";

Using replaceAll seems like the simplest cleanest way.使用replaceAll似乎是最简单最干净的方法。 (I can't vouch for fastest) (我不能保证最快)

'/var/www/site/Brand new document.docx'.replaceAll(' ', '')

See docs .请参阅文档

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. replaceAll() 方法返回一个新字符串,其中模式的所有匹配项都被替换。 The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.模式可以是字符串或正则表达式,替换可以是字符串或每次匹配调用的函数。

Easiest way to remove spaces from the string is use replace in this way从字符串中删除空格的最简单方法是以这种方式使用替换

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

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

You can use regex to remove spaces from string`您可以使用正则表达式从字符串中删除空格`

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

Although there are ways to use regex to remove spaces, there is a simple function that can remove all whitespace called .trim(); 虽然有办法使用正则表达式来删除空格,但是有一个简单的函数可以删除所有名为.trim();空格.trim(); :

var str = "abr a cadab ra";
str = str.trim();
//str = "abracadabra"
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);

The output:输出:

HelloWorld你好世界

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM