DEV Community

Cover image for How to Trim String in JavaScript
Samantha Ming
Samantha Ming

Posted on • Updated on

How to Trim String in JavaScript

Alt Text

It's super simple to remove whitespace from a string. To remove just the leading whitespace, you can use trimStart(). To remove trailing whitespace, use trimEnd(). Or remove it all with trim() πŸ™Œ

const string = "   hi   ";

string.trimStart(); // "hi   "
string.trimEnd();   // "   hi"
string.trim();      // "hi"

Trim Return Value

All trim methods, will return a new string. That means your original string will be left intact.

const string = "   hi   ";

string.trimStart(); // "hi   "
string.trimEnd();   // "   hi"
string.trim();      // "hi"

string;            // "   hi   "

What is Whitespace

So trim removes whitespace. So that is the white space created by:

  • space
  • tab
  • no-break space
  • line terminator characters

Trimming Line Terminator Characters

You might be wondering what are line terminator characters. Well, let's take a look at some examples.

'hi \n'.trim(); // "hi"

'hi \t'.trim(); // "hi"

'hi \r'.trim(); // "hi"

Multi-line String

In JavaScript, you can easily create multi-line strings using the Template Literals. So if you're wondering if trim works with that, you bet it does πŸ‘

const multiLine = `


multiline.trim(); // "hi"

Trimming Multiple Words

Remember trim only works for whitespace at the start and end. So it doesn't trim the space in between words.

'  hi there  '.trim(); // "hi there"

Multi-Line of Multiple Words

Same with multi-line, it only trims the beginning of the first word and the ending of the last word.

const multiLine = `



// Returns



Trim Aliases

trimStart vs trimLeft

trimStart removes the leading white space. So all the whitespace from the beginning of a string to the first non-whitespace character will be gone.

You might also see people using trimLeft(). Well, that's because it's an alias. It does the same thing.

const string = "   hi   ";

string.trimStart(); // "hi   "
string.trimLeft();  // "hi   "

trimEnd vs trimRight

trimEnd removes the trailing white space. So all the whitespace from the end of a string will be gone. The alias of this method is trimRight(). Again, they do the same thing.

const string = "   hi   ";

string.trimEnd();   // "   hi"
string.trimRight(); // "   hi"

Which one should I use?

So which one should you use? Well, let's see what the ECMAScript Specification says:

The property trimStart nad trimEnd are preferred. The trimLeft and trimRight property are provided principally for compatibility with old code. It is recommended that the trimStart property be used in new ECMAScript code.

trimStart and trimEnd for the win πŸ‘‘

Why are there aliases?

So trimLeft and trimRight were introduced first. However, the committee decided to propose a word change to trimStart and trimEnd instead. That's because it's more consistent to their other built-in methods, padStart and padEnd. Which makes sense to me, I think consistency is key and using the same language helps lessen confusion.

But for web compatibility reasons, they're keeping the old terms (trimLeft and trimRight) as aliases. So if your code is using the older methods, no problem, they will still work πŸ‘ However if you have the capacity, I'd recommend you changing it to use the official ones instead of the alias so you don't have two different methods floating around in your codebase. Remember it's all about that consistency 😎

Trim Methods Use Case


I mostly used trim(). Very handy to remove whitespace for a form input πŸ‘

<input type="text" id="search" />
const inputValue = document.getElementById('search').value.trim();

You can also use it to remove odd whitespaces in a sentence and format it properly. Essentially creating your very own sentence prettier πŸ’…

const uglySentence = "One  Two   Three Four   ";

const prettySentence = uglySentence
    .split(' ') // ["One", "", "Two", "", "", "Three", "Four", "", "", ""]
    .filter(word => word) // ["One", "Two", "Three", "Four"]
    .join(' '); // "One Two Three Four"

// βœ… Result
console.log(prettySentence); // "One Two Three Four"


I haven't used this before. But I can see where this can be handy. Take a markdown file. You would want to preserve the leading whitespaces. But with the trailing whitespaces, you might want to automatically get rid of it so it doesn't render out a confusing or unexpected result for your user.

- List Item
  - Sub List Item
  - Sub List Item


I don't have a great example for this one. But if I stayed with the markdown file example. We might want to prohibit nested listed items. However, we still want to preserve trailing whitespace. In markdown, if you use insert two whitespaces, it will create a line break. I'm going to denote whitespaces with a dot Β·, so you can see what's going on.

Markdown won't create a line break here


// Result
hi there

To force a line break, you can add 2 spaces.


// Result

So knowing this, you might not want to remove the trailing space. However, you still want to get rid of a nested list. In that case, then trimStart might be the one for you.

Browser Support

Support for trim() is pretty awesome! However, it's a bit limited for trimStart and trimEnd, that's because they were introduced later on.

Browser trim trimStart trimEnd
Chrome βœ… βœ… βœ…
Firefox βœ… βœ… βœ…
Safari βœ… βœ… βœ…
Edge βœ… βœ… βœ…
Internet Explorer βœ… ❌ ❌

Community Input


const string = '  hi   ';
string.replace(/ /g, ''); // "hi"

πŸ‘† Note: this solution will remove ALL whitespace from the string. To trim would be this:

let str = '      Samantha Ming      ';
let trimmedStr = str.replace(/^\s+ | \s+$/g, '');

console.log(trimmedStr); // "Samantha Ming"

Thanks @Jalaj


Thanks for reading ❀
Say Hello! Instagram | Twitter |

Top comments (8)

bytebodger profile image
Adam Nathaniel Davis • Edited

I understand that, if the ECMAScript specification favors trimStart() over trimLeft() and trimEnd() over trimRight(), then that's probably the standard we should follow. But I actually wonder if the standards committee might've been a bit shortsighted in their recommendations? Consider this example:

const myArabicString = '   Ψ«ΨΉΩ„Ψ¨ Ψ¨Ω†ΩŠ سريع   ';

Of course, both console.log() functions do the same thing. And if we use trimLeft(), I'm pretty certain that anyone reading the code would understand that we are trimming the space to the left of سريع. As far as I know, "left" and "right" are fairly universal ideas.

But if we use trimStart(), this strikes me as a potential source of confusion in a non-Anglo-centric world. The Arabic language - like a number of others - is read from right to left. And the "starting location" is relative to your own point of reference. So it's reasonable to think that an Arabic-speaking coder might look at the second console.log() and make the mistake of assuming that it will actually trim the space on the right side of the string. Because, if you're reading Arabic text, the right side of the string is the "start" of the string.

lito profile image

But start is not from start of text, is from start of string and string starts always at position 0 from left. Is not related with string as localized language, is related with string as an element of javascript language.

bytebodger profile image
Adam Nathaniel Davis • Edited

Yeah, I get that. And I'm not trying to imply that trimStart() is, in any way, "wrong". But we have two arbitrary names that could be used to describe the function. One of those names is universal - i.e., "left" is "left", everywhere. The other name is not universal. It forces you to think in terms of an "element of JavaScript", even though strings are very often associated with natural language and "start" and "end" mean different things, depending upon the natural language we're using. The standards group chose to recommend the meaning that is not universal. Hmm...

I'm not claiming it's any kinda huge tragedy. It would rarely cause anyone even the slightest of confusion. If you're a left-to-right native speaker like me (and most of us are), you'll probably never even think about the tiny little ambiguity. I just think that, if they'd thought that one through, they would have chosen the naming convention that is unambiguous.

There are only two hard things in computer science: cache invalidation and naming things. - Phil Karlton

samanthaming profile image
Samantha Ming

Oh! i wasn't aware of that! Thanks for sharing your insight. Hmm...I do wonder how they came up with this and if anyone brought this to their attention during the proposal stage. Looking at the proposal at github, it doesn't seem like there were any πŸ€”

jalaj profile image

The solution given in the Community Input removes all the whitespace from the string. That isn't trimming exactly. The correct way to do it should be...

let str = "      Samantha Ming      "
let trimmedStr = str.replace(/^\s+ | \s+$/g , '')    

console.log(trimmedStr)     // "Samantha Ming"
samanthaming profile image
Samantha Ming

OH good call! let me add your point to the code notes! Thanks for info πŸ‘

wrldwzrd89 profile image
Eric Ahnell

Thank you Samantha - such a common need, and easy to get lost in the weeds when the solution is right there.

samanthaming profile image
Samantha Ming

totally! JS is constantly improving, so often you don't have to look too far and they probably have a built-in solution. That's why I keep sharing, it's all about expanding our toolbox...we might not need it right away, but when we do, we can just grab it from our toolbox. Thanks Eric, happy you found the post helpful πŸ™‚