How to remove whitespaces from the beginning of a string in JS
Whitespaces in Java
In JavaScript, there is a method called, trimStart() in string. This method is used to remove the whitespaces only from the beginning of a string. The starting whitespace characters in the original string are deleted which produces a new string. The original string is unaffected by the trimStart() technique.
The whitespace symbols in JavaScript are the following:
- The “space” character.
- An asterisk (*) with a carriage return ().
- A new line of text.
- The “tab” character.
- A character with a vertical tab.
- A character for form feeds.
Syntax
String.trimStart();
Parameter
It doesn’t have any parameters.
Return value
trimStart() removes the beginning whitespace characters from the input string and returns a new string.
Example
var str = " eductive.io";//string declaration with whitespaceconsole.log("Input String >>", str); // print input stringconsole.log("String and it's length before using trimStart method >> ", str.length);var trimmedStr = str.trimStart();// trimStart methodconsole.log("After using trimStart method input String >>", trimmedStr);console.log("String and it's length after using trimStart method >> ", trimmedStr, trimmedStr.length);// Resultant string after removal of whitespaces.
Explanation
-
Line 1: We assign a string which contains whitespace into a variable
str. -
Line 2: We print the
strvariable. -
Line 3: We print the length of the
str. -
Line 4: After calling the
str.trimStart()method, we store the return value in to another variable calledtrimmedStr. -
Line 5: We print the variable
trimmedStr. -
Line 6: We finally print the
lengthof thetrimmedStr.
Note: We have removed the whitespaces from the beginning of the string using
trimStart()method so the length of thetrimmedStris reduced.