DEV Community

loading...

Removing Whitespace from Start and End

Randy Rivera
Once I truly put my mind on something, I won't ever stop.
・1 min read
  • Sometimes whitespace characters around strings are not wanted but are there. Typical processing of strings is to remove the whitespace at the start and end of it.

  • Let's write a regex and use the appropriate string methods to remove whitespace at the beginning and end of strings.

  • Note: The String.prototype.trim() method would work here, but for now you'll need to complete this challenge using regular expressions.

  • Ex:

let hello = "   Hello, World!  ";
let wsRegex = /^\s+|\s+$/g; 
let result =  hello.replace(wsRegex, ""); 
Enter fullscreen mode Exit fullscreen mode
  • result will be equal to the string Hello, World!

Discussion (0)