This is what you want:
function ltrim(str) {
if(!str) return str;
return str.replace(/^s+/g, '');
}
Also for ordinary trim in IE8+:
function trimStr(str) {
if(!str) return str;
return str.replace(/^s+|s+$/g, '');
}
And for trimming the right side:
function rtrim(str) {
if(!str) return str;
return str.replace(/s+$/g, '');
}
Or as polyfill:
// for IE8
if (!String.prototype.trim)
{
String.prototype.trim = function ()
{
// return this.replace(/^s+|s+$/g, '');
return this.replace(/^[suFEFFxA0]+|[suFEFFxA0]+$/g, '');
};
}
if (!String.prototype.trimStart)
{
String.prototype.trimStart = function ()
{
// return this.replace(/^s+/g, '');
return this.replace(/^[suFEFFxA0]+/g, '');
};
}
if (!String.prototype.trimEnd)
{
String.prototype.trimEnd = function ()
{
// return this.replace(/s+$/g, '');
return this.replace(/[suFEFFxA0]+$/g, '');
};
}
Note:
s: includes spaces, tabs , newlines
and few other rare characters, such as v, f and
.
uFEFF: Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
xA0: ASCII 0xA0 (160: non-breaking space) is not recognised as a space character
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…