Javascript 从文本中删除所有空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6623231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:31:06  来源:igfitidea点击:

Remove ALL white spaces from text

javascriptjquery

提问by Cecil Theodore

$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");

This is a snippet from my code. I want to add a class to an ID after getting another ID's text property. The problem with this, is the ID holding the text I need, contains gaps between the letters.

这是我的代码片段。我想在获取另一个 ID 的文本属性后向一个 ID 添加一个类。问题在于,包含我需要的文本的 ID 包含字母之间的间隙。

I would like the white spaces removed. I have tried TRIM()and REPLACE()but this only partially works. The REPLACE()only removes the 1st space.

我想删除空格。我试过了TRIM()REPLACE()但这只是部分有效。该REPLACE()只删除第一个空间。

回答by Flimzy

You have to tell replace() to repeat the regex:

你必须告诉 replace() 重复正则表达式:

.replace(/ /g,'')

The gcharacter means to repeat the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.

字是指通过重复整个字符串搜索。在此处阅读有关此内容以及 JavaScript 中可用的其他 RegEx 修饰符。

If you want to match all whitespace, and not just the literal space character, use \sinstead:

如果要匹配所有空格,而不仅仅是文字空格字符,请\s改用:

.replace(/\s/g,'')

回答by Pantelis

.replace(/\s+/, "") 

Will replace the first whitespace only, this includes spaces, tabs and new lines.

替换第一个空格,这包括空格、制表符和换行符。

To replace all whitespace in the string you need to use global mode

要替换字符串中的所有空格,您需要使用全局模式

.replace(/\s/g, "")

回答by Alberto Trindade Tavares

Using String.prototype.replacewith regex, as mentioned in the other answers, is certainly the best solution.

String.prototype.replace如其他答案中所述,使用正则表达式当然是最好的解决方案。

But, just for fun, you can also remove all whitespaces from a text by using String.prototype.splitand String.prototype.join:

但是,为了好玩,您还可以使用String.prototype.splitand删除文本中的所有空格String.prototype.join

const text = ' a b    c d e   f g   ';
const newText = text.split(/\s/).join('');

console.log(newText); // prints abcdefg