I worked on the below challenge for about 3 hours and none of my code was working. Decided to look at the solution to understand why I was not working. When I looked at the solution I was confused because I thought that \s to identify white spaces not to remove them... can someone give me hand and explain why the usage of \s instead of \S and why using the empty string ("") to get rid of the white spaces on both ends.
CHALLENGE
Write a regex and use the appropriate string methods to remove whitespace at the beginning and end of strings.
//SOLUTION
let hello = " Hello, World! ";
let wsRegex = /^\s+|\s+$/g;
let result = hello.replace(wsRegex, "");
\s
means whitespace characters in regex, like space, tab, etc.^
means the beginning of the string$
means the end of the string|
means OR (match the left side or the right side)+
means 1 or more (based off of the rule on the left)/a regex/g
the g
means "global", aka "match multiple times" since you could need to match at the beginning AND endSo the regex means:
/^\s+|\s+$/g
/ / Wrap the regex (how you do it in JS)
^\s+ Try to match at the beginning one or more whitespace chars
| Or...
\s+$ Try to match whitespace chars at the end
g Match as many times as you can
String.prototype.replace replaces the match(es) found in the regex with the string provided as the 2nd argument, in this case an empty string.
So the process internally is:
""
, removing those matches entirelylet hello = " Hello, World! ";
let wsRegex = /^\s+|\s+$/g;
let result = hello.replace(wsRegex, "");
console.log('"' + result + '"');
Most people use String.prototype.replaceAll instead of .replace
when they use the global flag
let hello = " Hello, World! ";
let wsRegex = /^\s+|\s+$/g;
let result = hello.replaceAll(wsRegex, "");
console.log('"' + result + '"');