JavaScript trim

The JavaScript trim function is a string function used to remove empty spaces from both the left and right sides of a string.

Whitespaces are the most common issue that developers face in an application. For instance, a user may enter the username (“admin “) with a black space at the beginning or end, and it does not match the current database record, so authentication fails. In such a case, use the JavaScript trim() function to remove the extra black spaces at the start and end of a string.

There are three types of string functions to remove the whitespaces on both sides. Apart from them, there is another function for custom trimming.

  • trim(): Removes whitespaces from both sides of a string.
  • trimStart(): Removes spaces from the beginning of a string.
  • trimEnd(): Removes blank spaces from the end of a string.
  • replace(): Use for the custom removal. It deletes unwanted characters, including whitespaces.

What is the JavaScript trim() function?

The trim() function removes the leading and trailing whitespaces or blank spaces of the string.

Whitespaces include:

  • Regula blank spaces (” “).
  • New lines (\n).
  • Tab spaces (\t).
  • Carriage returns (\r).
  • For feed (\f).
  • Other Unicode whitespace characters.

JavaScript trim() syntax

The syntax of the trim function to remove whitespaces from both sides of a string is

String_Object.trim()

As you can see from the syntax, it does not accept any parameter values.

Return Value: The JavaScript trim() function does not modify the existing string, which means it preserves the original string. Instead, it returns a completely new string with no whitespaces on either side of the string.

NOTE: If you pass a string without any blank spaces, the trim() function still returns a new string with the same text. It makes a copy of the original.

How JavaScript trim() function work?

As mentioned earlier, the trim() function only removes whitespaces from the beginning and end of a string. It does not remove spaces between the words.

In the following example, there are extra spaces at the beginning and end of the string. Apart from that, there is extra whitespace between the two states. When you see the result. The trim() removed the leading and trailing blank spaces and leaves the extra spaces in the middle as they are.

const s = "  Washington   California   " 
let n = s.trim() ;
console.log(n);
Washington   California

The JavaScript trim() function does not modify the original string. Instead, it creates a new string without any spaces or newlines.

let s = "\n \tCalifornia \n"
console.log(s)
let n = s.trim() ;
console.log(n);

        California 

California

TIP: Apart from the whitespaces, the trim() function won’t delete arbitrary characters or a set of characters (multiple characters). To remove them, use the string replace() function.

JavaScript trim() function examples

The following list of examples demonstrates the working functionality of the trim() function deletes unwanted spaces at the start and end of a string.

Trimming leading whitespaces of a string

In the example below, we use the JavaScript trim() function to remove blank spaces at the beginning of the string. As you can see, the declared starting has leading whitespaces.

let s = "   Hello";
let n = s.trim() ;
console.log(n);
Hello

Trimming trailing whitespaces of a string

Similar to the above, we can use the JavaScript trim() function to remove the whitespaces at the end of the string. Here, we declared a string with blank spaces at the end.

let s = "World     ";
let n = s.trim() ;
console.log(n);
World

Trimming whitespaces from both sides of a string

The real power of the trim() function comes when we apply it to a string with leading and trailing whitespaces. As we mentioned earlier, the JavaScript trim() function removes blank spaces from the beginning and end of a given string at a time.

let s = "     Hello, World!     ";
let n = s.trim() ;
console.log(n);
Hello, World!

JavaScript trim() function with tab and newline characters

Apart from the regular whitespaces, we can use the trim() function to handle tabs, new lines, and a mix of both.

Trimming Tab characters

For demonstration purposes, we declared a string with a tab space at the start and end of a message.

let s = "\t Tutorial Gateway \t";
let n = s.trim() ;
console.log(n);
Tutorial Gateway

JavaScript trim() function for trimming New Lines

In the example below, we used two newlines (\n) at the start of the string and one newline at the end. It means there are two empty lines followed by a welcome message, followed by another newline.

let s = "\n \nWelcome \n";
let n = s.trim() ;
console.log(n);
Welcome

Mixed whitespace

In the example below, we declare a string with a whitespace, a newline character (\n), and a tab character (\t) on both sides of a text. Next, we use the trim() function to remove those unwanted spaces from the given string.

let s = " \n\t   Welcome   \t \n ";
let n = s.trim() ;
console.log(n);
Welcome

JavaScript trim Function to remove spaces, tabs, and newlines

The following examples will help you understand how to use a trim function to remove whitespace characters or extra spaces from the original string.

Initially, we declared the String variable Str1 and assigned the corresponding value using the var str1 statement. The second line removes the white spaces from both the left and right sides of the Str1 variable.

var str3 removes only the leading or left-hand side using the JavaScript trim function. It deletes white spaces from the left-hand side.

In the next line, str4 deletes the trailing or Right-hand side of the string using the String Function. The following JavaScript statement removes white spaces from the right-hand side.

Next, we used the line terminator along with these objects. If you observe the above screenshot, the trim function is to delete terminators, such as \t and \n.

<!DOCTYPE html>
<html>
<head>
    <title>TRIM</title>
</head>
<body>
    <h1> JavaScriptTRIM</h1>
<script>
    var Str1 = "    Tutorial Gateway     ";
    var Str2 = Str1.trim();
    var Str3 = "    Tutorial Gateway".trim();
    var Str4 = "Tutorial Gateway     ".trim();
    var Str5 = " \t   Tutorial Gateway    \n ".trim();
 
    document.write(Str2 + "<br \>");
    document.write(Str3 + "<br \>");
    document.write(Str4 + "<br \>");
    document.write(Str5 + "<br \>");
</script>
</body>
</html>
JavaScript trim function Example

JavaScript trimStart() or trimLeft()

The trimStart() function, previously known as the trimLeft(), removes whitespaces from the beginning of the string. If the purpose is to remove the leading whitespaces, use the trimStart() function.

trimStart Syntax

The syntax of the trimStart() function is as shown below.

stringObject.trimStart()

Similar to the JavaScript trim() function, the trimStart() method won’t accept any parameters and returns a new string.

trimStart Example

In the example below, we declared two string variables, where the first one has whitespaces at the beginning. The second string has both the leading and trailing blank spaces. When you see the output, it removes the whitespaces from the start and leaves the blank spaces at the end of the string.

const s1 = "     New York"
let n1 = s1.trimStart() ;
console.log(n1);

const s2 = " California "
let n2 = s2.trimStart() ;
console.log(n2);
New York
California

JavaScript trimEnd() or trimRight()

The trimEnd() function, previously known as the trimRight(), removes whitespaces from the end of the string. If the purpose is to remove the trailing whitespaces, use the trimEnd() function.

trimEnd Syntax

The syntax of the trimEnd() function is as shown below.

stringObject.trimEnd()

Similar to the JavaScript trim() method, the trimEnd() function does not change the original string and returns a new string. It won’t accept any parameters.

trimEnd Example

In the example below, we declared two string variables with empty spaces at the end. The second string contains whitespaces at the start and end of a given text. When you see the output, it removes the trailing whitespaces and leaves the blank spaces at the start of the string.

const s1 = "New Jersey      "
let n1 = s1.trimEnd() ;
console.log(n1);

const s2 = " Texas "
let n2 = s2.trimEnd() ;
console.log(n2);
New Jersey
     Texas

Real-time examples of the JavaScript trim() function

The following examples are some of the real-time examples at the production level.

Trimming the Array Items

The following example shows an array of spring items where each item has enormous spaces. Next, the map function iterates over the list items. Here, the JavaScript trim() function removes the whitespaces from the individual string list items.

let users = ["John   ", "   Tracy   ", " Mike  "];

let cleanUsers = users.map(user => user.trim());
console.log(cleanUsers);
[ 'John', 'Tracy', 'Mike' ]

Instead of using a map, if you want to perform the same operation, follow the code below. From the example below, the for loop will iterate over the list items from the first index position to the last index position.

On each iteration, we access the individual array item and apply the trim function. By this, we can remove the empty spaces from all array items one after the other while completing the iterations.

TIP: This for loop approach won’t create a new array; instead, we modify the existing array.

let users = ["John   ", "   Tracy   ", " Mike  "];

for (let i = 0; i < users.length; i++) {
users[i] = users[i].trim();
}
console.log(users);
[ 'John', 'Tracy', 'Mike' ]

JavaScript trim() function for User Input Validation

The following example allows the user to enter the email address. Here, the trim function is used to remove the unnoticed spaces at the start and end of the email address. Next, we use the if else statement to check whether the user-given email is empty or not. If it is empty, inform the user that the email input is empty. Otherwise, a valid message with the user-given email is the console output.

let email = prompt("Enter the Email:").trim();
if (email === "")
{
console.log("Email address is empty");
}
else {
console.log("Valid", email);
}
   contact@tutorialgateway.org       
Valid contact@tutorialgateway.org

Use trim() in Form Validation

In the example below, we declared a string (username) with empty spaces on both sides. In the next line, we use the JavaScript trim() function to remove white spaces on both sides of the username.

The if statement checks whether the trimmed username is empty. If true, print the username is required statement at the console. Otherwise, the form submission message will be displayed.

Suppose you don’t use the trim function to remove empty spaces, then some users may submit blank spaces as a username, which is incorrect.

let username = "  admin   ";
let clean = username.trim();

if (clean === "")
{
console.log("Username is required");
}
else {
console.log("Form submitted");
}
Form submitted

In real-time, we use the text box to allow user to insert their username. For the sake of simplicity, we manually insert the text and check against.

document.getElementById("username").value;

JavaScript trim() function for Login Authentication

In the example below, we allow the user to enter the username and password for the login page. As there are possibilities of extra spaces in the username and password, we use the trim function to remove the leading and trailing spaces.

In the next line, the if else statement checks whether the user enter username and a password that match the existing credentials. If true, allow the user to login otherwise, inform the user about wrong credentials.

let username = prompt("Enter the Username:").trim();
let password = prompt("Enter the Password:").trim();

if (username === "admin" && password === "sample123")
{
console.log("Login Success");
}
else {
console.log("Wrong Credentials");
}
Login Success

JavaScript trim() function on a CSV file

In the example below, there is a CSV file. It has three rows, each row has information about the users, including full name, email address, and age. If you notice the entries, each user entry has leading and trailing white spaces. Before processing the data and entering the content into the database file, you must delete those extra spaces.

Here, the first for loop will iterate over the CSV file. The split() function splits each row in a CSV file into individual values based on the comma delimiter. It means on each for loop iteration, the items variable holds an individual row from the CSV data.

The nested for loop iterates over the items (row fetched for this iteration). They are the full name, email address, and age of a user. Inside the for loop, the trim() function deletes the whitespaces from the start and end of the individual items in that row.

let usersCSV = [
" Johny Depp , john@example.com , 30 ",
" David Miller , dave@example.com , 29 ",
" Jack Ryan , ryan@example.com , 38 "
];
for (let i = 0; i < usersCSV.length; i++) {
let items = usersCSV[i].split(",");

for (let j = 0; j < items.length; j++) {
items[j] = items[j].trim();
}
console.log(items);
}
[ 'Johny Depp', 'john@example.com', '30' ]
[ 'David Miller', 'dave@example.com', '29' ]
[ 'Jack Ryan', 'ryan@example.com', '38' ]

Cleaning API Data with trim() method

Similar to the above example, we can use the trim() function to clean the data received from the API. To demonstrate it, we declared an employee’s information, considering it as the API response.

Next, we used the trim() function to delete the leading and trailing blank spaces from the employee name, email, city, age, and salary.

let apiInfo = {
name: " David Miller ",
email: " miller@example.com ",
city: " New York ",
age: " 32 ",
Salary: " 100000 ",
};

apiInfo.name = apiInfo.name.trim();
apiInfo.email = apiInfo.email.trim();
apiInfo.city = apiInfo.city.trim();
apiInfo.age = apiInfo.age.trim();
apiInfo.Salary = apiInfo.Salary.trim();

console.log(apiInfo);
{
    name: 'David Miller',
        email: 'miller@example.com',
    city: 'New York',
    age: '32',
    Salary: '100000'
}

Integrating the JavaScript trim() with other string functions

The following example builds a universal string cleaner. It uses both the string trim() function and the replace() function.

Here, the trim() function deletes the unwanted leading and trailing spaces. The replace function removes blank spaces between words and adds a single space to separate two words.

function Universal(txt)
{
return txt.trim().replace(/\s+/g, ' ');
}

let text = " Happy New Year ";
console.log(Universal(text));
Happy New Year

If you want to perform the case-sensitive operations, use the toLowerCase() method to convert the string to lowercase.

return txt.trim().replace(/\s+/g, ' ').toLowerCase()

URL slug Generator with trim() method

The code below uses three string methods to generate a URL from a given SEO meta title. Here, the trim() function removes the blank spaces from both sides. The toLowercase() converts the meta title to lowercase. The replace() removes whitespaces between words and adds the (-) symbol between words.

function URLGeneration(title)
{
return title.trim().toLowerCase().replace(/\s+/g, '-');
}

let MetaTitle = " Tutorial Gateway ";
console.log(URLGeneration(MetaTitle));
tutorial-gateway

Alternatives to the JavaScript trim() function

The following are alternative methods for trimming leading and trailing extra spaces in a string.

Use replace() with a regular expression

The following example uses the string replace() function with a regular expression to remove leading and trailing white spaces. It acts the same as the JavaScript trim() function. It does not remove blank spaces between two words.

const text = "   United  Kingdom ";

const clean = text.replace(/^\s+|\s+$/g, "");
console.log(clean);
United  Kingdom

Use the expression below to delete the whitespaces between Hello and World.

text.replace(/\s+/g, "");

Using replaceAll() method

There is a built-in string replaceAll() function to replace all occurrences of a substring. We use replaceAll to replace blank spaces with nothing. It does not space the whitespaces between the words.

const text = "   United  Kingdom    ";

const clean = text.replaceAll(" ","");
console.log(clean);
UnitedKingdom

Use split() and join() functions

In the example below, the split() function splits the string into a number of items based on the empty space. The join() function joins them using a separator. Here, we set no space as the separator to remove the whitespaces.

const text = "   United Nations   ";

const clean = text.split(" ").join("");
console.log(clean);
UnitedNations

Using match() and join() method

The string match() function with a regular expression returns an array of strings (words) without any whitespaces. The join() function adds a single blank space between the words.

const text = "   United  Nations   ";

const clean = text.match(/\S+/g).join(" ");
console.log(clean);
United Nations

Using lodash

The lodash library has a built-in trim() function that acts as a JavaScript trim() function in a string object to remove unwanted spaces.

import _ from "lodash";
const text = " United Nations ";
const clean = _.trim(text);
console.log(clean);
United Nations

Apart from the whitespaces, the lodash trim() removes the unwanted characters. Here, it removes the # symbol at the beginning and end of a given string.

import _ from "lodash";
const text = "#####United Nations######";
const clean = _.trim(text, "#");
console.log(clean);
United Nations

Common Mistakes

JavaScript trim() function without assigning to a new variable

As mentioned earlier, the trim() function does not change the original string. So, we must assign the result to a new variable to get the trimmed data.

let text = "  Hi   "
text.trim()
console.log(text)
  Hi  

Fix

let text = "  Hi   "
let n = text.trim()
console.log(n)
Hi

Using the trim() function on a non-string

The trim() function applies to string data. If you use it on any other data type, it will throw an error. So, either you use the string data type or convert the existing data to a string to apply the trim() function.

let text = 123
console.log(text.trim())

Fix

let text = 123
console.log(String(text).trim())
123