在 javascript 中修剪?这段代码在做什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3387088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
trim in javascript ? what this code is doing?
提问by sushil bharwani
I was looking for a trim function in JavaScript which doesn't exist and some code on Googling suggests that use:
我在 JavaScript 中寻找一个不存在的修剪函数,谷歌上的一些代码建议使用:
function trimStr(str) {
return str.replace(/^\s+|\s+$/g, '');
}
I want to know how str.replace(/^\s+|\s+$/g, '')works. I understand that this is some form of regular expression but dont know what it is doing.
我想知道如何str.replace(/^\s+|\s+$/g, '')运作。我知道这是某种形式的正则表达式,但不知道它在做什么。
回答by Tatu Ulmanen
/^\s+|\s+$/gsearches for whitespace from either the beginning or the end of the string. The expression can be split into two parts, ^\s+and \s+$which are separated by |(OR). The first part starts from the beginning of the string (^) and includes as many whitespace characters it can (\s+). The second part does the same but in reverse and for the end using the dollar sign ($).
/^\s+|\s+$/g从字符串的开头或结尾搜索空格。表达式可以分为两部分,^\s+并\s+$用|(OR)分隔。第一部分从字符串 ( ^)的开头开始,并包含尽可能多的空白字符 ( \s+)。第二部分执行相同但相反的操作,最后使用美元符号 ( $)。
In plain english, the regular expression would go like this:
用简单的英语,正则表达式会是这样的:
Find as many whitespace characters from the beginning of the string as possible or as many whitespace characters from the end as possible.
从字符串的开头找到尽可能多的空白字符,或者从字符串的末尾找到尽可能多的空白字符。
Note that \smatches spaces, tabs and line breaks.
请注意,\s匹配空格、制表符和换行符。
The /gpart at the end enables global searching, which allows multiple replacements (eg. not just the beginning, but the end of the string also).
最后的/g部分启用全局搜索,允许多次替换(例如,不仅是开头,还包括字符串的结尾)。
回答by Matthew Flaschen
^is the beginning of the string, and $is the end. \smeans a whitespace character (which in JavaScript specifically means tab, vertical tab, form feed, space, non-break space, byte order mark, Unicode space separator (category Zs), line feed, carriage return, line separator, or paragraph separator), and +means 1 or more. |is alternation, a choice between two possibilities. gis the global flag. So the regex means the beginning, then one or more whitespace, or one or more whitespace, then the end. Then, we replace all matches (since it's global) with the empty string.
^是字符串的开头,$也是结尾。 \s表示空白字符(在 JavaScript 中具体表示制表符、垂直制表符、换页符、空格、不间断空格、字节顺序标记、Unicode 空格分隔符(Z 类)、换行符、回车符、行分隔符或段落分隔符) ,+表示 1 个或多个。 |是交替,两种可能性之间的选择。 g是全球旗帜。所以正则表达式意味着开始,然后是一个或多个空格,或者一个或多个空格,然后是结尾。然后,我们用空字符串替换所有匹配项(因为它是全局的)。
You might be interested in this blog post, which analyzes in more detail than you probably need :) the pros and cons of various trim functions.
您可能对这篇博文感兴趣,它比您可能需要的更详细地分析了各种修剪功能的优缺点。

