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

这是我的代码片段。我想在获得另一个ID的文本属性后向ID添加一个类。这样做的问题是,ID持有我需要的文本,包含字母之间的空白。

我想把空白去掉。我已经尝试了TRIM()和REPLACE(),但这只是部分工作。REPLACE()只删除第一个空格。


当前回答

简单的解决方法是:替换空格询问键值

val = val.replace(' ', '')

其他回答

现在你可以使用"replaceAll":

console.log(' a b    c d e   f g   '.replaceAll(' ',''));

将打印:

abcdefg

但并不是在所有可能的浏览器中都能运行:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

使用.replace(/\s+/g, ")可以;

例子:

this.slug = removeAccent(this.slug).replace(/\s+/g,'');
.replace(/\s+/, "") 

将只替换第一个空白,这包括空格,制表符和新行。

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

.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;
}