Remove leading and trailing whitespace from JavaScript String

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 whitespace 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 JavaScript 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



JavaScript function: removeWhitespaceUsingTrimMethod

function removeWhitespaceUsingTrimMethod {

		var str = "    This is whitespace string for testing purpose     ";
		var wsr = str.trim();



  • 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


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);



  • 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




Happy Coding !!
Happy Learning !!