W3cubDocs

/JavaScript

string.trimStart

The trimStart() method removes whitespace from the beginning of a string. trimLeft() is an alias of this method.

Syntax

str.trimStart();
str.trimLeft();

Return value

A new string representing the calling string stripped of whitespace from its beginning (left end).

Description

The trimStart() / trimLeft() methods return the string stripped of whitespace from its left end. trimLeft() or trimStart() do not affect the value of the string itself.

Aliasing

For consistency with functions like String.prototype.padStart the standard method name is trimStart. However, for web compatibility reasons, trimLeft remains as an alias to trimStart. In some engines this means:

String.prototype.trimLeft.name === "trimStart";

Examples

Using trimStart()

The following example displays the lowercase string 'foo ':

var str = '   foo  ';

console.log(str.length); // 8

str = str.trimStart();
console.log(str.length); // 5
console.log(str);        // 'foo  '

Specifications

Specification Status Comment
String.prototype.{trimStart,trimEnd} proposal Stage 1

Browser compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
Basic support 66
66
Yes
Uses the non-standard name: trimLeft
? 61
61
3.5
Uses the non-standard name: trimLeft
No 53 ?
Mobile
Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android iOS Safari Samsung Internet
Basic support 66
66
Yes
Uses the non-standard name: trimLeft
66
66
Yes
Uses the non-standard name: trimLeft
? 61
61
4
Uses the non-standard name: trimLeft
53 ? ?
Server
Node.js
Basic support 10.0.0

Polyfill

//https://github.com/FabioVergani/js-Polyfill_String-trimStart

(function(w){
    var String=w.String, Proto=String.prototype;

    (function(o,p){
        if(p in o?o[p]?false:true:true){
            var r=/^\s+/;
            o[p]=o.trimLeft||function(){
                return this.replace(r,'')
            }
        }
    })(Proto,'trimStart');

})(window); 


/*
ES6:
(w=>{
    const String=w.String, Proto=String.prototype;

    ((o,p)=>{
        if(p in o?o[p]?false:true:true){
            const r=/^\s+/;
            o[p]=o.trimLeft||function(){
                return this.replace(r,'')
            }
        }
    })(Proto,'trimStart');

})(window);
*/

See also

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimStart