Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Quick Question about Regular Expression Bracket (JS)

I'm trying to replace any multiple space characters with just a single space.

What is the difference between the following?

string.replace(/\s\s+/g,' ');

string.replace(/[\s+]/g,' ');

I first came up with the 2nd one, but, after a quick Google search, the first one appeared and worked correctly. My original (the 2nd one) did not work and I'm not sure why...

Thanks again!

2 Answers

Steven Parker
Steven Parker
225,756 Points

Let's look at what these expressions are saying:

string.replace(/\s\s+/g,' ');

This one says "look for 2 or more spacing characters, and replace them with a single space". \s is one spacing character, \s+ is one or more, so \s\s+ is two or more. This would be a good way to collapse spans of white space.

string.replace(/[\s+]/g,' ');

This says "look for a spacing character or a plus sign, and replace it with a space". The contents of a pair of brackets define a single character, and everything inside is a potential candidate. Inside the brackets, the plus sign loses its meaning of "one or more" and becomes just a plus sign. This would convert tabs and plus signs into spaces (not what you intended).

Thanks! I didn't know the + did not function inside of the [] operators.

Seth Kroger
Seth Kroger
56,409 Points

Since brackets in a regex mean "match any character inside the brackets" [\s+] means match a single whitespace or plus sign character. If you wanted to use + to mean "one or more" it would have to go outside like this [\s]+, but since there is only one character/class the brackets are redundant so it's just \s+

Thanks! I didn't know the + did not function inside of the [] operators.