2. Using string.replaceAll() Method
The replaceAll() method is a simple way to replace all occurrences of a specific character or pattern, such as spaces.
Syntax
string.replaceAll(' ', '');
Example
let str = "Learn JavaScript with Coding Ninjas";
let result = str.replaceAll(' ', '');
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output
LearnJavaScriptwithCodingNinjas
Explanation
replaceAll(' ', ''): Finds all spaces in the string and replaces them with an empty string.
This method is efficient and easy to use if your JavaScript version supports replaceAll() (introduced in ES2021).
3. Using string.trim() Method
The trim() method removes spaces only from the beginning and end of the string, leaving spaces between words untouched.
Syntax
string.trim();
Example
let str = " Hello World ";
let result = str.trim();
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output
Hello World
Explanation
trim(): Removes spaces from both ends of the string.
This method is useful when you want to clean up extra spaces at the start or end of user input.
4. Using Lodash _.trim() Method
Lodash is a popular utility library in JavaScript that provides the _.trim() method to remove spaces from the beginning and end of a string.
Syntax
_.trim(string);
Example
const _ = require('lodash'); // Import Lodash library
let str = " Learn JavaScript ";
let result = _.trim(str);
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output
Learn JavaScript
Explanation
_.trim(): Functions similarly to string.trim(), but comes with Lodash’s reliability and support for additional features.
This method is great if you’re already using Lodash in your project.
5. Using Regular Expressions with string.replace() Method
Regular expressions (regex) provide powerful ways to manipulate strings. You can use regex with the replace() method to remove all spaces.
Syntax
string.replace(/\s+/g, '');
Example
let str = " JavaScript is fun ";
let result = str.replace(/\s+/g, '');
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output
JavaScriptisfun
Explanation
- /\s+/g: Matches one or more whitespace characters globally in the string.
- replace(): Replaces all matched spaces with an empty string.
This method is efficient for removing spaces from the entire string, including multiple spaces between words.
6. Using string.match() with array.join() Method
The match() method can extract non-space characters, which can then be joined together to form a space-free string.
Syntax
string.match(/\S/g).join('');
Example
let str = " Coding Ninjas ";
let result = str.match(/\S/g).join('');
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output
CodingNinjas
Explanation
- /\S/g: Matches all non-whitespace characters globally.
- match(): Returns an array of matched characters.
- join(''): Combines the characters into a single string.
This method is particularly useful when you need to explicitly filter out spaces and keep all other characters intact.
Specifications
Removing spaces from a string in JavaScript can be done in multiple ways. Each method has its own use case & works slightly differently. Below, we’ll discuss the most common methods:
1. Using `replace()` with Regular Expressions
The `replace()` method is a powerful tool for string manipulation. When combined with regular expressions, it can remove all spaces from a string.
Let’s see how it works:
let str = "Hello World! This is a test string.";
let noSpaces = str.replace(/\s/g, '');
console.log(noSpaces);

You can also try this code with Online Javascript Compiler
Run Code
Output:
"HelloWorld!Thisisateststring."
- `\s` is a regular expression that matches any whitespace character (spaces, tabs, or line breaks).
- The `g` flag ensures that all occurrences of spaces are replaced, not just the first one.
- The second argument `''` is an empty string, which replaces the spaces with nothing.
- This method is efficient & works well for removing all types of whitespace.
2. Using `split()` & `join()`
Another approach is to split the string into an array of substrings using `split()` & then join them back together using `join()`.
let str = "Hello World! This is a test string.";
let noSpaces = str.split(' ').join('');
console.log(noSpaces);

You can also try this code with Online Javascript Compiler
Run Code
Output:
"HelloWorld!Thisisateststring."
- `split(' ')` splits the string at every space, creating an array of words.
- `join('')` combines the array elements into a single string without spaces.
- This method is simple & easy to understand but only removes spaces, not other whitespace characters like tabs or line breaks.
3. Using `trim()` for Leading & Trailing Spaces
If you only need to remove spaces at the beginning & end of a string, you can use the `trim()` method.
Example:
let str = " Hello World! ";
let trimmedStr = str.trim();
console.log(trimmedStr);

You can also try this code with Online Javascript Compiler
Run Code
Output:
"Hello World!"
- `trim()` removes spaces from both ends of the string but leaves spaces in the middle untouched.
- This method is useful for cleaning up user input, such as form fields.
Browser Compatibility
When working with JavaScript, it’s important to ensure that the methods you use are supported across all major browsers. Let’s check the compatibility of the methods we discussed:
1. `replace()` with Regular Expressions
The `replace()` method, along with regular expressions, is supported in all modern browsers, including:
- Chrome
- Firefox
- Safari
- Edge
- Opera
It also works in older browsers like Internet Explorer 9 & above.
2. `split()` & `join()`
These methods are part of the core JavaScript language & are supported in all browsers, including:
- Chrome
- Firefox
- Safari
- Edge
- Opera
- Internet Explorer (even older versions like IE6)
You can use this method without worrying about compatibility issues.
3. `trim()`
The `trim()` method is supported in all modern browsers, including:
- Chrome
- Firefox
- Safari
- Edge
- Opera
However, it is not supported in Internet Explorer 8 & below. If you need to support older browsers, you can use a polyfill or an alternative method.
Let’s take a polyfill for `trim()` to ensure compatibility with older browsers:
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
let str = " Hello World! ";
let trimmedStr = str.trim();
console.log(trimmedStr);

You can also try this code with Online Javascript Compiler
Run Code
Output:
"Hello World!"
- This polyfill adds the `trim()` method to the `String` prototype if it doesn’t already exist.
- It uses a regular expression to remove spaces & other whitespace characters from the beginning & end of the string.
Frequently Asked Questions
How do I remove spaces from both the start and end of a string in JavaScript?
You can use the trim() method, which removes spaces from the beginning and end of the string
What is the most efficient way to remove all spaces from a string in JavaScript?
Using the replaceAll() or replace() method with a regex pattern is highly efficien.
Can I use Lodash for string manipulation?
Yes, Lodash provides the _.trim() method to remove spaces from the start and end of a string.
Conclusion
Removing spaces from a string is a common task in JavaScript, especially when working with user input or formatting data. In this article, we discussed various methods, including split() with join(), replaceAll(), trim(), and regex-based approaches. Each method serves different use cases, allowing you to choose the best one based on your requirements.