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
Remove ALL white spaces from text
提问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 \s
instead:
如果要匹配所有空格,而不仅仅是文字空格字符,请\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.replace
with 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.split
and String.prototype.join
:
但是,为了好玩,您还可以使用String.prototype.split
and删除文本中的所有空格String.prototype.join
:
const text = ' a b c d e f g ';
const newText = text.split(/\s/).join('');
console.log(newText); // prints abcdefg