JavaScript Regex - Remove Whitespace from Start and End
Asked Answered
P

3

6

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, "");
Polymer answered 16/6, 2021 at 23:7 Comment(3)
The code identifies white space characters and then replaces them with empty string. By replacing something with nothing we get the same result as deleting something.Brunelleschi
It's finding whitespace and replacing what it finds with an empty string, aka removing itMisreckon
.... you decided to implement .trim() functionCircle
J
12
  • \s means whitespace characters in regex, like space, tab, etc.
  • ^ means the beginning of the string
  • $ means the end of the string
  • | means OR (match the left side or the right side)
  • + means 1 or more (based off of the rule on the left)
  • /a regex/g the g means "global", aka "match multiple times" since you could need to match at the beginning AND end

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 + '"');
Janitress answered 16/6, 2021 at 23:24 Comment(1)
Thanks for the detail explanation. It makes complete sense now.Polymer
W
0

The second argument of replace is for what you will replace from the match(es) of the first argument.

The regex will match/select the spaces on the beginning (^) and on the end ($) of the string, and then will be replaced by "".

When you use the regex /(\S)/g you're matching everything but spaces, in this case you will use something like hello.replace(/(\S)/g, '$1');

$1 means the first group of your regex.

Whorish answered 16/6, 2021 at 23:19 Comment(0)
F
-2

let str = "__ @!Hello World___-!! "

console.log(str); //"__ @!Hello World___-!! "

console.log(str.replace(/^[^a-zA-Z0-9]*|[^a-zA-Z0-9]*$/g, '')); //"Hello World"
Fatima answered 14/3, 2023 at 4:28 Comment(1)
The question is about removing whitespace, this answer removes everything except alphanumerics.Hilmahilt

© 2022 - 2024 — McMap. All rights reserved.