Thursday, February 27, 2020

Regular Expressions: Remove Whitespace from Start and End

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


Explanation :(/^\s+|\s+$/g;)

  1. caret symbol ^ looks at the start of string
  2. dollar symbol $ looks at the end of string
  3. The | is an OR operator
  4. \s+ looks for one or more white spaces 
  5. The g flag is needed to match all the spaces that are at the beginning OR at the end. Otherwise it would match only the first part of the regex, and the second part only if the first part doesn’t match anything



No comments:

Post a Comment

Mixed Content: The page at xxx was loaded over HTTPS, but requested an insecure

 Mixed Content: The page at ' https ://www.test.com/signup.aspx' was loaded over HTTPS, but requested an insecure script ' http ...