Javascript - How to remove the white space at the start of the string
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(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
if (!String.prototype.trimStart)
{
String.prototype.trimStart = function ()
{
// return this.replace(/^\s+/g, '');
return this.replace(/^[\s\uFEFF\xA0]+/g, '');
};
}
if (!String.prototype.trimEnd)
{
String.prototype.trimEnd = function ()
{
// return this.replace(/\s+$/g, '');
return this.replace(/[\s\uFEFF\xA0]+$/g, '');
};
}
Note:
\s: includes spaces, tabs \t, newlines \n and few other rare characters, such as \v, \f and \r.
\uFEFF: Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
\xA0: ASCII 0xA0 (160: non-breaking space) is not recognised as a space character
Try to use javascript's trim()
function, Basically it will remove the leading and trailing spaces from a string.
var string=' This is test';
string = string.trim();
DEMO
So as per the conversation happened in the comment area, in order to attain the backward browser compatibility just use jquery's $.trim(str)
var string=' This is test';
string = $.trim(string)
You can use String.prototype.trimStart(). Like this:
myString=myString.trimStart();
An if you want to trim the tail, you can use:
myString=myString.trimEnd();
Notice, this 2 functions are not supported on IE. For IE you need to use polyfills for them.