|
| 1 | +--- |
| 2 | +Title: '.trimStart()' |
| 3 | +Description: 'Removes whitespace characters from the start (left side) of a string.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Web Development' |
| 7 | +Tags: |
| 8 | + - 'Methods' |
| 9 | + - 'Strings' |
| 10 | +CatalogContent: |
| 11 | + - 'introduction-to-javascript' |
| 12 | + - 'paths/front-end-engineer-career-path' |
| 13 | +--- |
| 14 | + |
| 15 | +The **`trimStart()`** method removes whitespace characters from the beginning of a string. It returns a new string with leading whitespace removed, leaving the original string unchanged. This method is also available as `trimLeft()`, which is an alias for `trimStart()`. |
| 16 | + |
| 17 | +Whitespace characters include spaces, tabs, line breaks, and other Unicode whitespace characters. |
| 18 | + |
| 19 | +## Syntax |
| 20 | + |
| 21 | +```pseudo |
| 22 | +string.trimStart() |
| 23 | +``` |
| 24 | + |
| 25 | +**Parameters:** |
| 26 | + |
| 27 | +The `trimStart()` method does not take any parameters. |
| 28 | + |
| 29 | +**Return value:** |
| 30 | + |
| 31 | +Returns a new string with whitespace removed from the beginning of the original string. The original string remains unchanged. |
| 32 | + |
| 33 | +## Example |
| 34 | + |
| 35 | +The following example demonstrates how `trimStart()` removes leading whitespace: |
| 36 | + |
| 37 | +```js |
| 38 | +const greeting = ' Hello, World!'; |
| 39 | +const trimmedGreeting = greeting.trimStart(); |
| 40 | + |
| 41 | +console.log(greeting); |
| 42 | +console.log(trimmedGreeting); |
| 43 | +console.log(greeting.length); |
| 44 | +console.log(trimmedGreeting.length); |
| 45 | +``` |
| 46 | + |
| 47 | +The output of this code is: |
| 48 | + |
| 49 | +```shell |
| 50 | + Hello, World! |
| 51 | +Hello, World! |
| 52 | +16 |
| 53 | +13 |
| 54 | +``` |
| 55 | + |
| 56 | +In this example, `trimStart()` removes the three leading spaces from the string, reducing its length from 16 to 13 characters. |
| 57 | + |
| 58 | +## Codebyte Example |
| 59 | + |
| 60 | +Run the following code to see `trimStart()` in action: |
| 61 | + |
| 62 | +```codebyte/javascript |
| 63 | +// Example with various whitespace characters |
| 64 | +const text1 = " JavaScript"; |
| 65 | +const text2 = "\t\tProgramming"; |
| 66 | +const text3 = "\n\nCoding"; |
| 67 | +
|
| 68 | +console.log("Original:", text1); |
| 69 | +console.log("Trimmed:", text1.trimStart()); |
| 70 | +
|
| 71 | +console.log("Original:", text2); |
| 72 | +console.log("Trimmed:", text2.trimStart()); |
| 73 | +
|
| 74 | +console.log("Original:", text3); |
| 75 | +console.log("Trimmed:", text3.trimStart()); |
| 76 | +
|
| 77 | +// Example showing that trailing spaces are preserved |
| 78 | +const text4 = " Both sides "; |
| 79 | +console.log("Original length:", text4.length); |
| 80 | +console.log("After trimStart length:", text4.trimStart().length); |
| 81 | +``` |
0 commit comments