Signup/Sign In
PUBLISHED ON: AUGUST 27, 2021

JavaScript trimStart() and trimEnd() Method

Earlier, we had to use String.trim() method (was introduced in ES5) to remove the white space from the string. It removes the extra whitespace from both the side (beginning and end). But what if we want to remove the whitespace from a particular side only.

So, to solve this problem, ECMAScript 2019 or ES10 introduced two new functions, which are given below:

  • String.trimStart()
  • String.trimEnd()

Let's discuss each of them in detail.

String trimStart() Method

As the name suggests, the String.trimStart() method trims the whitespace from the beginning of the string. The whitespace character can be spaces, tabs, etc.

Syntax

trimStart()

Return Value

  • A new string is returned without whitespace at the beginning of it.
  • If there is no whitespace at the beginning of the string, a new string is still returned without throwing an error.

Example 1

In this example, we are going to trim the white space which is present at the beginning of the string using trimStart() method.

<!DOCTYPE html>
<html>
<head>
	<title>String.trimStart()</title>
</head>
<body>
	<script type="text/javascript">
		const message = '        Welcome to Studytonight.';
		console.log(message);
		console.log(message.trimStart()); 
	</script>
</body>
</html>

Output

We first printed the string without using the trimStart() method then we printed the string using trimStart() method.

output

String trimEnd() Method

The String.trimEnd() method removes the whitespace from the end of the string. The trimRight() method is an alias of this method.

Syntax

trimEnd()

Return Value

  • A new string is returned without whitespace at the end of it.
  • If there is no whitespace at the end of the string, a new string is still returned without throwing an error.

Example 2

In the given example, we have created a string and specified extra white space at the end of it. We used trimEnd() method to remove the extra white space which is present at the end of the string.

<!DOCTYPE html>
<html>
<head>
	<title>String.trimEnd()</title>
</head>
<body>
	<script type="text/javascript">
		const message = 'Welcome to Studytonight.          ';
		console.log(message);
		console.log(message.trimEnd()); 
	</script>
</body>
</html>

Output

output

Conclusion

In this lesson, we have learned two new string methods: trimStart() and trimEnd(). The trimStart() method is used to trim the whitespace from the beginning of the string, and the trimEnd() method is used to remove the white space at the end of the string.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight