简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM