$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");
这是我的代码片段。我想在获得另一个ID的文本属性后向ID添加一个类。这样做的问题是,ID持有我需要的文本,包含字母之间的空白。
我想把空白去掉。我已经尝试了TRIM()和REPLACE(),但这只是部分工作。REPLACE()只删除第一个空格。
$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");
这是我的代码片段。我想在获得另一个ID的文本属性后向ID添加一个类。这样做的问题是,ID持有我需要的文本,包含字母之间的空白。
我想把空白去掉。我已经尝试了TRIM()和REPLACE(),但这只是部分工作。REPLACE()只删除第一个空格。
当前回答
使用. replace (\ s / g,”)
这样问题就解决了。
快乐编码!!
其他回答
使用.replace(/\s+/g, ")可以;
例子:
this.slug = removeAccent(this.slug).replace(/\s+/g,'');
使用String.prototype.replace与regex,正如在其他答案中提到的,当然是最好的解决方案。
但是,只是为了好玩,你也可以使用String.prototype.split和String.prototype.join来删除文本中的所有空白:
Const text = ' a b c d f g '; const newText = text.split(/\s/).join("); console.log (newText);//打印abcdefg
function RemoveAllSpaces(ToRemove)
{
let str = new String(ToRemove);
while(str.includes(" "))
{
str = str.replace(" ", "");
}
return str;
}
** 100%工作
使用replace(/ +/g,'_'): let text = "我爱你" 文本=文本。取代(/ + / g , '_') // 替换为下划线(“_”) console.log(text) //我爱你
使用. replace (\ s / g,”)
这样问题就解决了。
快乐编码!!