Dealing with strings in JavaScript requires deep knowledge of how to perform different manipulations properly. Often there is a need to format the available text somehow, for example, remove unnecessary spaces between the words. Luckily, JavaScript offers a special method for removing whitespace from the beginning and the end of the text - trim()
.
It does not require any parameters to be passed. You can simply call it using your string variable. The example below illustrates how easy it is to format a string using the trim()
method. Note, that it does not modify the initial string. It creates a new one without spaces on both ends. Thus, you can see that even after calling the function, the string you have created at the beginning is still the same.
string = " Test string ";
console.log(string.trim()); // logs "Test string"
console.log(string); // logs " Test string "
Notes on trim() method
This method is very convenient as it allows you to remove all kinds of spaces: regular spaces, tabulations, non-breaking spaces and the symbols of line ending (LF – line feed, CR – carriage return etc.).
There are even more flexible ways to format your string in JavaScript. In the situations when you need to remove the whitespace from one side use trimLeft()
or trimRight()
methods.
string = " Test string ";
console.log(string.trimLeft()); // logs "Test string "
console.log(string.trimRight()); // // logs " Test string"
However, in some situations trim()
might not suffice since it only clears the spaces at the beginning and the end of your string. Note how in the above example the space between “Test” and “string” still remains. For cases when you need to delete spaces between the characters inside your sentence too, a more complicated procedure has to be performed.
Firstly, you need to split your string into an array using split()
method, take a space to be a separator and pass it as a parameter. Then with the help of join()
method, you can combine the array of words again using an empty string as a parameter. The below code illustrates how to remove all the spaces in your string by means of only two functions.
string = " Te st str ing ";
array = string.split(" ").join("");
console.log(array); // logs "Teststring"
Alternate ways of removing whitespace
Unfortunately, some older browser versions may not support the trim()
function, so you might need to create your own method for deleting the whitespace. However, this way requires knowledge of regular expressions. You will need to create a pattern, use it to find the spaces in your text and then replace them with an empty string using the self-titled function replace()
.
In order to create a correct pattern let’s dive a bit deeper into regular expressions. First of all you need to mark the boundaries of your pattern by putting it inside the forward slashes: /…/
.
The next step is to mark a whitespace; the metacharacter for it is \s
(don't mix it up with \S
which is for non-space characters). This marking matches the main forms of spacing in the ASCII system (\n
– new line, \f
– new page, \t
– tabulation). Keep in mind that your text may contain not one but several spaces in a row so in order to remove all of them you need to add a plus to your pattern: /\s+/
.
Finally, you need to make this expression actually look for all the spaces. There is a special modifier for that purpose: g
. Generally, regular expressions stop searching right after the first match, so we need the g
modifier to make it look for all the possible matches in the string.
Now when your regular expression looks like this:/\s+/g
you can pass it as a parameter into the replace()
method. It accepts two arguments: a character that you need to change and the new symbol that will be the substitute. So the correct implementation is: replace(/\s+/g, “”)
. The below example puts the theory into practice.
string = " Te st str ing ";
new_string = string.replace(/\s+/g, "");
console.log(new_string);
// The output is "Teststring"
Being familiar with the regular expressions you can as well make your own function for removing spaces from the beginning or the end only. Take the same pattern as you have already created and add the circumflex (^
) to search at the beginning of the line: /^\s+/g
.
For removing spaces at the end of your text use a dollar sign: /\s+$/g
. If you put a vertical bar between the two expressions, you will remove the space from both the beginning and the end of the string: /^\s+|\s+$/g
.
In order to check whether these expressions work or not you can use the string.length
property and see if the length of your text changes after space removal. In the below example there is a string of 15 characters with 3 spaces at the beginning of the text and 1 space at the end of it. The output illustrates that the created regular expressions work properly.
Example 1:
string = " Test string ";
console.log("Initial string length: " + string.length);
// Initial string length: 15
new_string1 = string.replace(/^\s+/g,'');
console.log("After left spaces removal: " + new_string1.length);
// After left spaces removal: 12
Example 2:
new_string2 = string.replace(/\s+$/g, '');
console.log("After right spaces removal: " + new_string2.length);
// After right spaces removal: 14
Example 3:
new_string3 = string.replace(/^\s+|\s+$/g, '');
console.log("After both sides spaces removal: " + new_string3.length);
// After both sides spaces removal: 11
Going further you can make your function even more universal by adding an m
modifier. It makes your expression delete the spaces from the beginning and the end of each line in your text and not the whole string.
JavaScript provides flexible tools for removing spaces from your string. In case if the built-in methods don’t work in your browser or you need them to be more specific, it’s quite easy to create your own function using regular expressions.