This write-up will guide you to omit space from the string’s start and end in JavaScript.
How to Remove/Omit Space From the Start and End of String in JavaScript?
To remove space from the string’s start and end in JavaScript, you can use:
Let’s discuss the mentioned approaches one by one!
Method 1: Remove the Spaces From the String’s Start and End in JavaScript Using trim() Method
The “trim()” method removes the specified character from both sides of a string without any change in the original string. You can apply this method to remove the blank spaces in the provided string value from its start and end.
Syntax
Here, “string” refers to the string value from which the whitespaces will be removed.
Example
In the example below, we will declare a variable named “removeSpace” and store a string value that has many whitespaces at the start and end:
Apply the “trim()” method on the string value. This will result in the removal of blank spaces from the start and end positions of the string value:
Finally, we will display the resultant string value without spaces on the console:
As you can see, we have successfully removed spaces from the specified string:
Method 2: Remove Space From Start and End of String in JavaScript Using replace() Method
The “replace()” method searches for a string value without any change in the original string value. We will utilize this method to search for the spaces using a regular alternative-based expression that searches and matches with two alternative patterns.
Syntax
Here, “searchValue” is the value that needs to be searched and replaced with “newValue()”.
Overview the following example.
Example
Now, we will apply the “replace()” method string with a regular expression “/^\s+|\s+$/gm”. The given two alternative regex patterns will search for the spaces at the string’s start and end. If found, it will be replaced by an empty string:
Finally, we will log the updated string value without the spaces on the console:
Output
We have compiled all the simplest methods to remove space from the start and end of the string in JavaScript.
Conclusion
To remove space from the start and end of a String in JavaScript, you can apply the “trim()” method directly on the initialized string or the “replace()” method along with a regular expression as its argument in order to search for the blank spaces and replace them with an empty string. This article guided about removing space from the string’s start and end in JavaScript.