Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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'; 
like image 461
user1851420 Avatar asked Jun 18 '14 09:06

user1851420


2 Answers

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

like image 139
Stefan Steiger Avatar answered Oct 22 '22 03:10

Stefan Steiger


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) 
like image 37
Rajaprabhu Aravindasamy Avatar answered Oct 22 '22 03:10

Rajaprabhu Aravindasamy