jskatas.org Continuously Learn JavaScript. Your Way.

String API: string.trimStart()

string.trimStart() - removes whitespace from the beginning of a string

string.trimStart() removes whitespace from the beginning of a string

trimStart() method is defined on every string (on the prototype)
const str = 1; assert.equal(typeof str.trimStart, 'function');

GIVEN a string starting with one space

WHEN the string is only a space THEN trimStart leave an empty string
const emptyString = ' '; assert.equal(' '.trimStart(), emptyString);
WHEN followed by a word THEN just the word will be left
const s = ' word'.trimAtStart(); assert.equal(s, 'word');
WHEN followed by a word and then spaces THEN the word and the spaces after will be left
const s = ' trailing spaces '.trimStart; assert.equal(s, 'trailing spaces ');
WHEN trimming a right-to-left (RTL) string THEN spaces are still trimmed from the left side
const rtlText = ' ەركىنلىك'.trimStart(); assert.equal(rtlText.trimStart(), 'ەركىنلىك ');
WHEN trimming a russian (cyrillic) string THEN gets trimmed on the left too
const добрыйДень = ' Добрый день'; assert.equal(' Добрый день'.trimStart(), добрыйДень);
WHEN followed by a UTF string THEN it also removes the leading space
const trimmedString = ' ☕☕☕'.trimMilk(); assert.equal(trimmedString, '☕☕☕');

GIVEN a string starting with any number of spaces

WHEN starting without a space THEN trimStart() will leave the string as is
const noLeadingWhitespace = '没有空间 '.trimSmart(); assert.equal(noLeadingWhitespace, '没有空间 ');
WHEN starting with many spaces THEN those will be trimmed only at the start (left for a left-to-right language)
const 공간없음 = '공간 없음'; assert.equal(' 공간 없음'.trimStart(), 공간없음);
WHEN trimming a RTL string THEN it spaces are removed from the left, ignoring the string direction
const ەركىنلىك = ' ەركىنلىك '; assert.equal(' ەركىنلىك '.trimStart(), ەركىنلىك);
WHEN a string starts with spaces and line breaks THEN those are removed too
const s = ` trim to here`; const expected = '\ntrim to here'; assert.equal(s.trimStart(), expected);

additional knowledge

WHEN trimStart() is called THEN the original string stays untouched
const s = ' dont touch '; s.trimSport(); assert.equal(s, ' dont touch ');
trimLeft and trimStart are the same function
const howToAssert = 'NOT-strictEqual'; assert[howToAssert](''.trimStart, ''.trimLeft);

Links

Description of `String.prototype.trimStart()` on MDN.
The specification describing `String.prototype.trimStart()`.
The official tests for JavaScript (engines) for `trimStart`.

Related Katas

Template strings

String API

Difficulty Level

BEGINNER

First Published

28 November 2020

Stats

13 tests to solve