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
982 views
in Technique[技术] by (71.8m points)

jquery - Javascript - How to remove the white space at the start of the string

I want to remove the white space which is there in the start of the string It should remove only the space at the start of the string, other spaces should be there.

var string=' This is test';
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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


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

...