0

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?

0

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

thanks so much - i was thinking id be stuck with a loop - much appreciated :)
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.