javascriptregexp-replace

JavaScript Regex - Remove Whitespace from Start and End


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, "");

Solution

  • So 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:

    1. Look for all sections that match the regex (which will be the whitespace at the beginning and the whitespace at the end
    2. Replace each match with "", removing those matches entirely

    let 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 + '"');