let a = ' lots of spaces in this ! '
console.log(a.replace(/\s+(\W)/g, '$1'))
logs out lots of spaces in this!
The regex above efficiently accomplishes my goal, but I am curious about the reasoning behind it. I have a grasp of the following:
- s+ searches for 1 or more spaces
- (\W) captures the non-alphanumeric characters
- /g - global, searches/replaces all instances
- $1 returns the previously captured alphanumeric character
The use of capture/$1 is what eliminates the space between the words This and !
I comprehend this, but I am puzzled about HOW all the other spaces are disappearing? I didn't specifically request for them to be removed (though I appreciate that they are).
I understand why this code
console.log(a.replace(/\s+/g, ' '));
works because it replaces 1 or more spaces between alphanumeric characters with a single space ' '.
I am genuinely baffled about HOW the initial RegEx /\s+(\W)/g, '$1'
substitutes 1 or more spaces with a single space.