What is the best way to trim() in javascript

前端 未结 19 1964
眼角桃花
眼角桃花 2020-11-29 06:32

The question says it all; JS doesn\'t seem to have a native trim() method.

19条回答
  •  感动是毒
    2020-11-29 06:51

    Well, as a lot of people always says, the trim function works pretty well, but if you don't want to use a whole framework just to perform a trim, it may be useful to take a look at its implementation. So here it is:

    function( text ) { return (text || "").replace( /^(\s|\u00A0)+|(\s|\u00A0)+$/g, "" );}
    

    The main advantages I see in this implementation, comparing to other solution already proposed here are:

    • The 'g' flag that allows you to perfom a trim on a multi-line string
    • The (text || "") syntax that ensure that the function will always work, even if the argument passed is null or undefined.

提交回复
热议问题