trim in javascript ? what this code is doing?

淺唱寂寞╮ 提交于 2019-11-30 07:58:06

问题


I was looking for a trim function in JavaScript which doesn't exist and some code on Googling suggests that use:

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.


回答1:


/^\s+|\s+$/g searches 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 ($).

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 \s matches spaces, tabs and line breaks.

The /g part at the end enables global searching, which allows multiple replacements (eg. not just the beginning, but the end of the string also).




回答2:


^ is the beginning of the string, and $ is the end. \s means 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. g is 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.

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.



来源:https://stackoverflow.com/questions/3387088/trim-in-javascript-what-this-code-is-doing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!