简体   繁体   English

如何解释Crockford的JavaScript Trim函数?

[英]How to interpret Crockford's JavaScript Trim function?

I'm going through the JavaScript Programming Language series by Douglas Crockford and came across this expression in his trim function: 我正在阅读Douglas Crockford的JavaScript Programming Language系列,并在他的trim函数中遇到了这个表达式:

String.prototype.trim = function () {
  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

I get what it does but how in the world does it work? 我了解它的作用,但它在世界上如何运作?

You should grab a tool like expresso , where you can step through the regex... 您应该使用expresso之类的工具,在其中可以逐步执行正则表达式...

^\\s* - Whitespace at the beginning of the line or string, with any number of repetitions ^\\s* -行或字符串开头的空白,可重复任意次数

(\\S*(\\s+\\S+)*) - Capture group, number "$1" in your example. (\\S*(\\s+\\S+)*) -捕获组,在您的示例中为数字“ $ 1”。

\\S*(\\s+\\S+)* - Anything but whitespace, any number of repetions \\S*(\\s+\\S+)* -除空格之外的任何东西,可重复任意次数

(\\s+\\S+)* - Another capture group, which looks for whitespace with one or more repetitions and anything other than whitespace with one or more repetitions. (\\s+\\S+)* -另一个捕获组,它查找具有一个或多个重复的空白以及具有一个或多个重复的空白以外的任何内容。

\\s*$ - Any number of whitespaces at the end of the line or string. \\s*$ -行或字符串末尾的任意数量的空格。

What it looks like in Expresso... Expresso中的外观...

Expresso屏幕截图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Crockford的伪经典继承部分中的函数构造函数 - Function constructor in Crockford's pseudoclassical inheritance section 对道格拉斯·克罗克福德的对象函数感到困惑 - Confused about Douglas Crockford's object function Crockford 书中 Javascript 中的记忆 - Memoization in Javascript from Crockford's book 解释这个 javascript 函数是如何工作的(在 Douglas Crockford 'How Javascript Works' 中找到) - explain how this javascript function works (found in Douglas Crockford 'How Javascript Works') 理解crockford的函数,它返回一个带有变量值的函数 - understanding crockford's function that returns a function with a variable value Douglas Crockford 的“Javascript:好的部分”第 5.5 章 - Douglas Crockford's "Javascript: The Good Parts" Chapter 5.5 Crockford的Javascript Applicative Order Y Combinator语法构造解释? - Crockford's Javascript Applicative Order Y Combinator syntax construct explanation? 克罗克福德书中的“方法”方法:Javascript:The Good Parts - “method” method in Crockford's book: Javascript: The Good Parts crockford的JavaScript构造函数模式真的应该更快吗? - Is crockford's JavaScript constructor pattern really supposed to be faster? Douglas Crockford的书中关于Function.prototype的“方法” - 'method' on Function.prototype in Douglas Crockford's book
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM