Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中修剪字符串?(Trim string in JavaScript?)

如何修剪JavaScript中的字符串?

  ask by Vinod translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

All browsers since IE9+ have trim() method for strings.

(自IE9 +起,所有浏览器都具有trim()方法来处理字符串。)

For those browsers who does not support trim() , you can use this polyfill from MDN :

(对于不支持trim()浏览器,可以使用MDN中的以下polyfill:)

if (!String.prototype.trim) {
    (function() {
        // Make sure we trim BOM and NBSP
        var rtrim = /^[suFEFFxA0]+|[suFEFFxA0]+$/g;
        String.prototype.trim = function() {
            return this.replace(rtrim, '');
        };
    })();
}

That said, if using jQuery , $.trim(str) is also available and handles undefined/null.

(也就是说,如果使用jQuery ,则$.trim(str)也是可用的,并且可以处理未定义/空值。)


See this:

(看到这个:)

String.prototype.trim=function(){return this.replace(/^s+|s+$/g, '');};

String.prototype.ltrim=function(){return this.replace(/^s+/,'');};

String.prototype.rtrim=function(){return this.replace(/s+$/,'');};

String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|
)s+|s+(?:$|
))/g,'').replace(/s+/g,' ');};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...