trim in javascript ? what this code is doing?

前端 未结 2 955
醉酒成梦
醉酒成梦 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:19

    /^\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).

提交回复
热议问题