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

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

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


当前回答

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

例如:

const stripped = '    My String With A    Lot Whitespace  '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'

其他回答

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

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

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

使用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

正则表达式用于删除空白

\s+

var str = “Visit Microsoft!”; var res = str.replace(/\s+/g, “”); console.log(res);

or

[ ]+

var str = “Visit Microsoft!”; var res = str.replace(/[ ]+/g, “”); console.log(res);

删除字符串开头的所有空白

^[ ]+

var str = “Visit Microsoft!”; var res = str.replace(/^[ ]+/g, “”); console.log(res);

删除字符串末尾的所有空白

[ ]+$

var str=“Visit Microsoft! "; var res = str.replace(/[ ]+$/g, “”); console.log(res);

    var mystring="fg gg";
   console.log(mystring.replaceAll(' ',''))
function RemoveAllSpaces(ToRemove)
{
    let str = new String(ToRemove);
    while(str.includes(" "))
    {
        str = str.replace(" ", "");
    }
    return str;
}
let str = 'a big fat hen clock mouse '
console.log(str.split(' ').join(''))
// abigfathenclockmouse