In this article, we will discuss how to remove leading and trailing whitespace from a JavaScript String
Often JavaScript is used to display string returned from back-end systems. Sometimes, string returned from backend consists of either leading or trailing whitespaces and in some case contains whitespaces at both ends
So, we need to remove those leading & trailing whitespaces from string returned before displaying to end user/client system
Remove leading and trailing whitespace from String :
- Using trim() method which works only in higher version browsers
- Using replace() method which works in all browsers
1. Using trim() method – in selected browsers :
Syntax:
testStr.trim();
JavaScript function: removeWhitespaceUsingTrimMethod
Output:
Explanation :
- Removes only leading & trailing whitespaces
- Internally, it invokes replace() method to trim both leading/trailing whitespaces
- In earlier version, trim() method wasn’t available
- Therefore, developers are forced to write/code their own logic using replace() method which helps to replace oldString with newString
2. Using replace() method – works in all browsers :
Syntax:
testStr.replace(rgExp, replaceText);
str.replace(/^\s+|\s+$/g, '');
JavaScript function: removeWhitespaceUsingReplaceMethod
function removeWhitespaceUsingReplaceMethod {
var str = " This is whitespace string for testing purpose ";
var wsr = str.replace(/^\s+|\s+$/g, '');
alert( wsr);
}
Output:
Explanation:
- Replace methods helps to remove both leading and trailing spaces
- In fact, it doesn’t work to replace only leading & trailing space but whichever regular expression matches then it will get replaced with new string passed in the 2nd argument
Some cool tips :
- str.replace(/\s+$/g, ”); –> is used to remove only trailing whitespaces
- str.replace(/^\s+/g, ”); –> is used to remove only leading whitespaces
- str.replace(/\”/g, ”); –> is used to remove double-quotes where /g indicates any of number of occurrences
- str.replace(/\s/g,”); –> is used to remove all spaces including spaces in between 2 words of a String
References:
- https://www.w3schools.com/jsref/jsref_trim_string.asp
- https://docs.microsoft.com/en-us/scripting/javascript/reference/trim-method-string-javascript
- https://www.w3schools.com/jsreF/jsref_replace.asp
- https://docs.microsoft.com/en-us/scripting/javascript/reference/replace-method-string-javascript
Happy Coding !!
Happy Learning !!