What is the best way to trim() in javascript

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

提交回复
热议问题