简体   繁体   English

JavaScript 删除字符串中的多个空格

[英]JavaScript remove multiple spaces in a string

Multiple consecutive spaces are causing me a headache in my JS script.多个连续的空格让我在我的 JS 脚本中感到头疼。 I tried doing this:我试过这样做:

 const originalStr = 'Hello there how are you' const actual = originalStr.replace(/ /g, ' ') const expected = 'Hello there how are you' console.log(`originalStr = '${originalStr}'`) console.log(`actual = '${actual}'`) console.log(`expected = '${expected}'`) console.log(`actual === expected...`, actual === expected)

But as you can see it's not working.但正如你所见,它不起作用。 It's failing when there are 3 or more consecutive spaces.当有 3 个或更多连续空格时,它会失败。 Is there a simple way to ensure that there are no consecutive spaces?有没有一种简单的方法来确保没有连续的空格? TIA TIA

Just modify your regex slightly:只需稍微修改您的正则表达式:

 const originalStr = 'Hello there how are you' const actual = originalStr.replace(/ +/g, ' ') const expected = 'Hello there how are you' console.log(`originalStr = '${originalStr}'`) console.log(`actual = '${actual}'`) console.log(`expected = '${expected}'`) console.log(`actual === expected...`, actual === expected)

Edit your regex with / +/g使用/ +/g编辑您的正则表达式

 const originalStr = 'Hello there how are you' const actual = originalStr.replace(/ +/g, ' ') const expected = 'Hello there how are you' console.log(`originalStr = '${originalStr}'`) console.log(`actual = '${actual}'`) console.log(`expected = '${expected}'`) console.log(`actual === expected...`, actual === expected)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM