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

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

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


当前回答

** 100%工作

使用replace(/ +/g,'_'): let text = "我爱你" 文本=文本。取代(/ + / g , '_') // 替换为下划线(“_”) console.log(text) //我爱你

其他回答

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

例如:

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

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

** 100%工作

使用replace(/ +/g,'_'): let text = "我爱你" 文本=文本。取代(/ + / g , '_') // 替换为下划线(“_”) console.log(text) //我爱你

let str = 'a big fat hen clock mouse '
console.log(str.split(' ').join(''))
// abigfathenclockmouse

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

例子:

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