What is the best way to trim() in javascript

前端 未结 19 1821
眼角桃花
眼角桃花 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:45

    Why not just modify the String prototype? Why not steal the trim function from an open source library, like I did here with YUI? (Do you really need to load and entire framework for this simple taks?) Put them together and you get this:

    String.prototype.trim = function() {
        try {
            return this.replace(/^\s+|\s+$/g, "");
        } catch(e) {
            return this;
        }
    }
    
    var s = " hello ";
    alert(s.trim() == "hello"); // displays true
    
    0 讨论(0)
  • 2020-11-29 06:45

    I use this.

        String.prototype.trim = function() {
            return this.replace(/^\s+|\s+$/g,"");
        }
    
    0 讨论(0)
  • 2020-11-29 06:48

    A slightly tinier version of @Pat's.

    return str.replace( /^\s+|\s+$/g, '' );
    
    0 讨论(0)
  • 2020-11-29 06:49

    I know this question is ancient but now, Javascript actually does have a native .trim()

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

    0 讨论(0)
  • 2020-11-29 06:50

    Actually, with jQuery this seems to be the way:

    jQuery.trim(string)
    

    (Reference)

    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题