In this blog post you’ll learn how to remove spaces from string using JavaScript. We’ll remove spaces from the beginning, end, and within a string in JavaScript
We’ll use methods to remove spaces from stirring:
- split() and join() method.
- Forloop and trim().
- Replace() method.
Remove Spaces Present Between And Sides of the String.
Way 1: split() and join() method.
With this method, we will first split the string using spaces to create an array. Then, we will join the elements of the array without any spaces.
JavaScript
// Example 1.
let string = " Hello welcome to maketechstuff.com ";
let output = string.split(" ").join("");
console.log(output);
Output:
Way 2: Split() and forloop.
First, we will split the string using spaces to create an array. Then, we will run a for loop and store each array element in a separate variable sequentially.
JavaScript
// Example 2.
let string = " Hello welcome to maketechstuff.com ";
let output = "";
let split = string.trim().split(" ");
for (let i = 0; i < split.length; i++) {
const element = split[i];
output += element;
}
console.log(output);
Output:
Way 3: Replace method
We will replace all spaces, including multiple spaces (such as " "), with no spaces ("") using the replace method with regular expressions.
JavaScript
// Example 3.
let string = " Hello welcome to maketechstuff.com ";
let output = string.replace(/\s+/g, "");
console.log(output);
Output:
Way 4: Split() and filter method.
JavaScript
// Example 4.
let string = " Hello welcome to maketechstuff.com ";
let output = "";
let split = string.trim().split(" ");
let new_array = split.filter(function (split) { return split })
output = new_array.join("")
console.log(output);
So that's how you can remove spaces present between and sides of the string. If you have any question or suggestion you can write in the comment section.
You may like:
- How to replace multiple spaces in a string with single space using JavaScript.
- How to capitalize the first letter of word in a string using JavaScript.
- How to change the text to uppercase and lowercase using JavaScript.
- Detect count and display the number of spaces in string using JavaScript.
Share your thoughts.