- How to Trim String in JavaScript
- trimEnd vs trimRight
- Which one should I use?
- Why are there aliases?
- Trim Methods Use Case
- Browser Support
- Community Input
- Resources
- Top comments (8)
- String.prototype.trim()
- Try it
- Syntax
- Return value
- Examples
- Using trim()
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- JavaScript String trim()
- Description
- See Also:
- Syntax
- Parameters
- Return Value
- Related Pages
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- # How to Trim String in JavaScript
- # What is Whitespace
- # Trimming Line Terminator Characters
- # Multi-line String
- # Trimming Multiple Words
- # Multi-Line of Multiple Words
- # Trim Aliases
- # trimStart vs trimLeft
- # trimEnd vs trimRight
- # Which one should I use?
- # Why are there aliases?
- # Trim Methods Use Case
- # Browser Support
- # Community Input
How to Trim String in JavaScript
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 👍
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
hi there // Result hi there
To force a line break, you can add 2 spaces.
hi·· there // Result hi there
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.
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"
Resources
Top comments (8)
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 = ' ثعلب بني سريع '; console.log(myArabicString.trimLeft()); console.log(myArabicString.trimStart());
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.
String.prototype.trim()
The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string.
To return a new string with whitespace trimmed from just one end, use trimStart() or trimEnd() .
Try it
Syntax
Return value
A new string representing str stripped of whitespace from both its beginning and end. Whitespace is defined as white space characters plus line terminators.
If neither the beginning or end of str has any whitespace, a new string is still returned (essentially a copy of str ).
Examples
Using trim()
The following example trims whitespace from both ends of str .
const str = " foo "; console.log(str.trim()); // 'foo'
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Mar 26, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
JavaScript String trim()
Remove spaces with replace() using a regular expression:
Description
The trim() method removes whitespace from both sides of a string.
The trim() method does not change the original string.
See Also:
Syntax
Parameters
Return Value
Related Pages
Browser Support
trim() is an ECMAScript5 (ES5) feature.
ES5 (JavaScript 2009) fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
# How to Trim String in JavaScript
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:
# 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 = ` hi `; 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.
# 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 = ` hi there `; // Returns "hi there"
# 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
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 👍
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
hi there // Result hi there
To force a line break, you can add 2 spaces.
hi·· there // Result hi there
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.
# 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"