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";

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);
*/

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

Browser compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
trimStart 66
66
4
Uses the non-standard name: trimLeft
12
12
Uses the non-standard name: trimLeft
61
61
3.5
Uses the non-standard name: trimLeft
No 53
53
15
Uses the non-standard name: trimLeft
12
Mobile
Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
trimStart 66
66
≤37
Uses the non-standard name: trimLeft
66
66
18
Uses the non-standard name: trimLeft
61
61
4
Uses the non-standard name: trimLeft
47
47
14
Uses the non-standard name: trimLeft
12 9.0
9.0
1.0
Uses the non-standard name: trimLeft
Server
Node.js
trimStart 10.0.0
10.0.0
0.12
Uses the non-standard name: trimLeft

See also

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