RegEx Course Final Challenge

I’ve just managed to complete the final regex challenge on the beta course, but not without introducing an extra variable.

Write a regex and use the appropriate string methods to remove whitespace at the beginning and end of strings.

let hello = "   Hello, World!   ";
let wsRegex = /^\s*/; // Change this line
let wsRegex2 = /\s*$/; // Change this line
let result = hello.replace(wsRegex, "").replace(wsRegex2, "");

I feel like I’ve skipped around the challenge rather than properly completing it since I’ve created two separate regular expressions and used the replace method to apply both of them.

Any input appreciated.

what’s wrong with that? To me, it doesn’t look bad in any ways.

You can combine more than 1 regular expression with the | symbol:

let hello = "   Hello, World!   ";
let wsRegex = /^\s*|\s*$/g;            // <- note the g flag needed here
let result = hello.replace(wsRegex, "");
6 Likes