Trim() Method for Strings in JavaScript
The trim()
method is applied on strings to remove whitespaces from the beginning and end of the string. Whitespaces include space, tabs, no break-spaces and so on.
Syntax
string.trim();
The method does not take any argument. It is called directly on the string.
Return Value
The return value of this method is the same string but without whitespaces at both sides. The method does not manipulate the string itself but returns the same string stripped of the whitespaces it has.
Example 1
let string1 = " The name of our game ";
console.log(string1.trim());
console.log(string1);
// Expected Output
// "The name of our game"
// " The name of our game "
As seen in the code above, the method doesn’t tamper with the string itself. The string us untouched.
Example 2
let string2 = " A string ";
let trimmedString2 = string2.trim();
console.log(string2);
console.log(trimmedString2);
// Expected Output
// " A string "
// "A string"
Alternative
Without this method (or if not supported), whitespaces can only be removed by applying regex. For example, we can create a function which returns a new string from a previous string but without whitespaces. Take a look at this example
function removeWhiteSpace(str) {
let reg = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
let newStr = str.replace(reg, '');
return newStr;
}
let str = " Yes ";
let trimmedStr = removeWhiteSpace(str);
console.log(trimmedStr);
// Expected Output
// "Yes"
Polyfill
If the method is available natively, you can add it to the string prototype object provided by javascript.
By adding the following code to the top of your script, the trim()
method would be created.
if (String.prototype.trim !== undefined) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
The regex applied above is similar to the regex in our alternative function above. First, we check if the trim method exists, and if it doesn’t, we create it. By doing this, you can begin using the trim method.
trimStart() and trimEnd()
These methods are available only in ECMAScript10 (ES2019) and not older versions. Hence they can only be used in modern browsers with upgraded javascript. However, with polyfill, you can add them.
They are similar to trim()
but they split its functions.
trimStart() is a method applied on strings which only removes the whitespaces from the beginning of the sentence (often called leading whitespaces)
trimEnd() on the other hand, is a method applied on strings which only removes the whitespaces from the end of the sentence (often called trailing whitespaces)
Their applications are similar to trim()
. Their respective syntaxes are
string.trimStart()
string.trimEnd()
Their return values are the same string but stripped of the whitespaces it may possess.
As observed, trimStart()
+ trimEnd()
make up trim()