Possible Duplicate:
Replace all spaces in a string with '+'可能的重复:将字符串中的所有空格替换为'+'
$("#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()只删除第1个空格。
2 个解决方案
#1
852
You have to tell replace() to repeat the regex:
您必须告诉replace()重复regex:
.replace(/ /g,'')
The g character means to repeat the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
g字符表示在整个字符串中重复搜索。请阅读本文以及JavaScript中可用的其他正则表达式修饰符。
If you want to match all whitespace, and not just the literal space character, use \s
as well:
如果您想匹配所有空格,而不仅仅是文字空格字符,也可以使用\s:
.replace(/\s/g,'')
#2
243
.replace(/\s+/, "")
should work (Regex that removes all spaces)
应该工作(删除所有空格的Regex)
or you can try this
或者你可以试试这个
.replace(/\s/g, "")
(globally replace spaces)
(全球替换空格)
#1
852
You have to tell replace() to repeat the regex:
您必须告诉replace()重复regex:
.replace(/ /g,'')
The g character means to repeat the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
g字符表示在整个字符串中重复搜索。请阅读本文以及JavaScript中可用的其他正则表达式修饰符。
If you want to match all whitespace, and not just the literal space character, use \s
as well:
如果您想匹配所有空格,而不仅仅是文字空格字符,也可以使用\s:
.replace(/\s/g,'')
#2
243
.replace(/\s+/, "")
should work (Regex that removes all spaces)
应该工作(删除所有空格的Regex)
or you can try this
或者你可以试试这个
.replace(/\s/g, "")
(globally replace spaces)
(全球替换空格)