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

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

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


当前回答

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

例子:

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

其他回答

现在你可以使用"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

我不明白当我们可以简单地使用replaceAll时,为什么我们需要在这里使用regex

let result = string.replaceAll(' ', '')

结果将存储没有空格的字符串

使用替换(/ \ s + / g”),

例如:

const stripped = '    My String With A    Lot Whitespace  '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'
let str = 'a big fat hen clock mouse '
console.log(str.split(' ').join(''))
// abigfathenclockmouse
function RemoveAllSpaces(ToRemove)
{
    let str = new String(ToRemove);
    while(str.includes(" "))
    {
        str = str.replace(" ", "");
    }
    return str;
}