trim in javascript ? what this code is doing?

前端 未结 2 944
醉酒成梦
醉酒成梦 2020-12-16 10:40

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.repla         


        
2条回答
  •  伪装坚强ぢ
    2020-12-16 11:14

    ^ 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.

提交回复
热议问题