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

发布于 2024-11-06 02:45:06 字数 212 浏览 1 评论 0原文

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

输入:

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

输出:

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

How to remove spaces in a string? For instance:

Input:

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

Output:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

つ可否回来 2024-11-13 02:45:06

这?

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 是“全局”标志,表示匹配所有 \s(空格)。

关于 + 的详细解释可以在这里找到

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

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).

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.

林空鹿饮溪 2024-11-13 02:45:06

最短和最快str.replace(/ /g, '');


基准:

这是我的结果 - (2018.07.13) MacOs High Sierra 10.13.3 on Chrome 67.0 .3396(64 位)、Safari 11.0.3(13604.5.6)、Firefox 59.0.2(64 位)):

短字符串

类似于 OP 问题中的示例的短字符串

在此处输入图像描述

最快的解决方案所有浏览器均为 / /g (regexp1a) - Chrome 17.7M(操作/秒)、Safari 10.1M、Firefox 8.8M。对于所有浏览器来说最慢的是split-join解决方案。将 更改为 \s 或将 +i 添加到正则表达式会减慢处理速度。

LONG 字符串

对于约 300 万个字符的字符串,结果为:

  • regexp1a:Safari 50.14 ops/sec、Firefox 18.57、Chrome 8.95
  • regexp2b:Safari 38.39、Firefox 19.45、Chrome 9.26
  • < strong>split-join:Firefox 26.41、Safari 23.10、Chrome 7.98,

您可以在您的计算机上运行它:https://jsperf.com/remove-string-spaces/1

SHORTEST and FASTEST: 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) ):

SHORT strings

Short string similar to examples from OP question

enter image description here

The fastest solution on all browsers is / /g (regexp1a) - Chrome 17.7M (operation/sec), Safari 10.1M, Firefox 8.8M. The slowest for all browsers was split-join solution. Change to \s or add + or i to regexp slows down processing.

LONG strings

For string about ~3 milion character results are:

  • regexp1a: Safari 50.14 ops/sec, Firefox 18.57, Chrome 8.95
  • regexp2b: Safari 38.39, Firefox 19.45, Chrome 9.26
  • split-join: Firefox 26.41, Safari 23.10, Chrome 7.98,

You can run it on your machine: https://jsperf.com/remove-string-spaces/1

冷情妓 2024-11-13 02:45:06
var a = b = " /var/www/site/Brand new   document.docx ";

console.log( a.split(' ').join('') );
console.log( b.replace( /\s/g, '') ); 

有两种方法可以做到这一点!

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!

阳光下慵懒的猫 2024-11-13 02:45:06

以下@rsplak回答:实际上,使用split/join方式比使用regexp更快。查看性能测试用例

所以

var result = text.split(' ').join ('')

的运行速度比

var result = text.replace(/\s+/g, '')

在小文本上这不相关,但对于时间很重要的情况,例如在文本分析器中,尤其是当与用户互动,这一点很重要。


另一方面,\s+ 可以处理更广泛的空格字符。在\n\t中,它还匹配\u00a0字符,这就是  在使用 textDomNode.nodeValue 获取文本时被转入。

所以我认为这里可以得出这样的结论:如果你只需要替换空格 ' ',请使用split/join。如果符号类可以有不同的符号 - 使用replace(/\s+/g, '')

Following @rsplak answer: actually, using split/join way is faster than using regexp. See the performance test case

So

var result = text.split(' ').join('')

operates faster than

var result = text.replace(/\s+/g, '')

On small texts this is not relevant, but for cases when time is important, e.g. in text analisers, especially when interacting with users, that is important.


On the other hand, \s+ handles wider variety of space characters. Among with \n and \t, it also matches \u00a0 character, and that is what   is turned in, when getting text using textDomNode.nodeValue.

So I think that conclusion in here can be made as follows: if you only need to replace spaces ' ', use split/join. If there can be different symbols of symbol class - use replace(/\s+/g, '')

这样的小城市 2024-11-13 02:45:06

您还可以使用 JS 的最新字符串方法之一: 全部替换

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

You also use one of the latest string methods of JS: replaceAll

'/var/www/site/Brand new document.docx'.replaceAll(' ', '');
雨巷深深 2024-11-13 02:45:06

简单的方法

someString.replace(/ /g, '');
// or
someString.replace(/\s/gm, '');

easy way

someString.replace(/ /g, '');
// or
someString.replace(/\s/gm, '');
遮云壑 2024-11-13 02:45:06
var input = '/var/www/site/Brand new document.docx';

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

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

alert(input);

单击此处查看工作示例

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

你在我安 2024-11-13 02:45:06

没有正则表达式,它只适用于一次。

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

这更快更简单!
在某些情况下可以帮助你们中的一些人。

Without regexp, it works fine for only one occurrence.

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

This is faster as simple !
Could help some of you in some cases.

标点 2024-11-13 02:45:06

从字符串中删除空格的最简单方法是以这种方式使用替换

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

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, '');
空城之時有危險 2024-11-13 02:45:06
  var output = '/var/www/site/Brand new document.docx'.replace(/ /g, ""); 
    or
  var output = '/var/www/site/Brand new document.docx'.replace(/ /gi,"");

注意:虽然您使用“g”或“gi”来删除空格,但两者的行为相同。

如果我们在替换函数中使用“g”,它将检查是否完全匹配。但如果我们使用“gi”,它会忽略大小写。

参考点击此处

  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.

If we use 'g' in the replace function, it will check for the exact match. but if we use 'gi', it ignores the case sensitivity.

for reference click here.

风流物 2024-11-13 02:45:06

您可以使用正则表达式从字符串中删除空格`

let str = '/var/www/site/Brand new document.docx';
let result = 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, '');
疑心病 2024-11-13 02:45:06

使用 replaceAll 似乎是最简单、最干净的方法。

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

请参阅文档

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

Using replaceAll seems like the simplest cleanest way.

'/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. 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.

舟遥客 2024-11-13 02:45:06

正则表达式 + Replace()

虽然正则表达式可能会更慢,但在许多用例中,开发人员仅一次操作几个字符串,因此考虑速度是无关紧要的。尽管 / / 比 /\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 可以对字符串进行进一步的链式操作。

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";

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.

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.

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";
孤檠 2024-11-13 02:45:06
var str = '/var/www/site/Brand new document.docx';

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


----------

var str = '/var/www/site/Brand new document.docx';

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


----------

如果没结果 2024-11-13 02:45:06
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);

输出:

HelloWorld

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文