JavaScript 正则表达式 - 删除开头和结尾的空格

Cri*_* M. 4 javascript regexp-replace

我花了大约 3 个小时来解决下面的挑战,但我的代码都不起作用。决定查看解决方案以了解我为什么不工作。当我查看解决方案时,我很困惑,因为我认为 \s 是用来识别空格而不是删除它们...有人可以帮我解释一下为什么使用 \s 而不是 \S 以及为什么使用空字符串( "") 去掉两端的空格。

挑战

编写正则表达式并使用适当的字符串方法来删除字符串开头和结尾的空格。

//SOLUTION

let hello = "   Hello, World!  ";
let wsRegex = /^\s+|\s+$/g; 
let result = hello.replace(wsRegex, "");
Run Code Online (Sandbox Code Playgroud)

Sam*_*jig 12

  • \s表示正则表达式中的空白字符,例如space,tab等。
  • ^表示字符串的开头
  • $表示字符串的结尾
  • |表示OR(匹配左侧或右侧)
  • +表示 1 个或多个(基于左侧的规则)
  • /a regex/g意味着g“全局”,又名“多次匹配”,因为您可能需要在开头和结尾进行匹配

所以正则表达式的意思是:

/^\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
Run Code Online (Sandbox Code Playgroud)

String.prototype.replace将正则表达式中找到的匹配项替换为第二个参数提供的字符串(在本例中为空字符串)。

所以内部流程是:

  1. 查找与正则表达式匹配的所有部分(这将是开头的空格和结尾的空格)
  2. 将每个匹配项替换为"",完全删除这些匹配项

/^\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
Run Code Online (Sandbox Code Playgroud)

大多数人在使用全局标志时使用String.prototype.replaceAll而不是.replace

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

console.log('"' + result + '"');
Run Code Online (Sandbox Code Playgroud)