简体   繁体   中英

JavaScript remove multiple spaces in a string

Multiple consecutive spaces are causing me a headache in my JS script. 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. Is there a simple way to ensure that there are no consecutive spaces? 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

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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