This is the perfect sol basically.
Don’t know if it has been posted before but
/^\s+|\s+$/g
is probably the most intuitive answer there is, and its not situation specific.
^\s+ looks for one or more blankspaces at the beginning of a string
| acts as an “or”
\s+$ looks for one or more blankspaces at the end of a string
include the g flag so that the one at the beginning and at the end will be selected.
whole code looks like this:
let hello = " Hello, World! ";
let wsRegex = /^\s+|\s+$/g; // Change this line
let result = hello.replace(wsRegex, “”); // Change this line
This is my code
let hello = " Hello, World! ";
let wsRegex = /Hello, World!/; // Change this line
let result = hello.match(wsRegex); // Change this line
This is my solution
let hello = " Hello, World! ";
let wsRegex = /^\s*(\S.*\S)\s*$/; // Change this line
let result = hello.replace(wsRegex,"$1");
Exactly what I was looking for! Thanks for the “or” operator hint.
what about other strings? Your solution did not cover all the situation
Can you explain what is achieved in the parenthesis by using
.* and \S
?
I think this is the ‘optimal’ solution. I passed this exercise only by specifying the exact string that should be kept in a capture group - but I couldn’t figure out how to write an abstract regex that would cover any string that happened to be between the whitespace. Well done!
In english, I’d say that expression means:
zero or more of characters immediately followed by one non-space character
Essentially, \S
is used to locate and include the last character before the trailing whitespace
This regex will only match this string. It will not work for any other string (like, " Hello World "). @ballabani has written the right solution.
I don’t think it will work if there is no space before and after the “Hello, world!”.
Instead of using \s+ , I used s* , i.e.,
let wsRegex = /^\s*|\s*$/g
It’s been a while but as far as I recall the objective of the exercise was to remove whitespace from the beginning and the end of a word. If there is no whitespace then everything is fine. That’s why we use s+ not s*
Hope this helps.
let wsRegex = /^\s+|\s+$/g;