This is the LGZX company's interview question, asks the JS string to add a method, removes the white space character (including Space, tab, page break, etc.) on both sides of the string.
Copy Code code as follows:
String.prototype.trim = function () {
Return This.replace (/[(^\s+) (\s+$)]/g, "");//will remove whitespace from the string
Return This.replace (/^\s+|\s+$/g, ""); //
Return This.replace (/^\s+/g, ""). Replace (/\s+$/g, "");
}
Jquery1.4.2,mootools use
Copy Code code as follows:
function Trim1 (str) {
Return Str.replace (/^ (\s|\xa0) +| ( \S|\XA0) +$/g, "");
}
Jquery1.4.3,prototype use, this method removes G to slightly improve performance when handling strings on a small scale
Copy Code code as follows:
function trim2 (str) {
Return Str.replace (/^ (\s|\u00a0) +/, ""). Replace (/(\S|\U00A0) +$/, "");
}
Steven Levithan, after performing a performance test, proposes the fastest-performing clipping string in JS, which is better when dealing with long strings.
Copy Code code as follows:
function trim3 (str) {
str = str.replace (/^ (\s|\u00a0) +/, "");
for (var i=str.length-1; i>=0; i--) {
if (/\s/.test (Str.charat (i))) {
str = str.substring (0, i+1);
Break
}
}
return str;
}
The last thing to mention is the addition of the native Trim method (15.5.4.20) to string in ECMA-262 (V5). In addition, the Trimleft, TrimRight method is added to string in the Molliza Gecko 1.9.1 engine.