09 April 2009

0 JavaScript code to trim leading and trailing spaces from a string

This JavaScript code can be used for removing unnecessary spaces from a string. That is, we can use this JavaScript snippet to trim leading and trailing spaces from a string

//To trim leading or trailing spaces

function trimString (str) {

   return str.replace(/^\s+/g, '').replace(/\s+$/g, '');  

}

The thing to note here is that the first .replace actually removes the leading blank spaces where as the second replace removes the trailing blank space. The first parameter in the .replace is known as regular expression.

 

  • ^ indicates the beginning of the string. Using a ^ metacharacter requires that the match start at the beginning.
  • $ indicates the end of the string. Using a $ metacharacter requires that the match end at the end of the string.
  • \s represents the any single space character.
  • /g represents the global search for all occurrence of the pattern 



0 comments:

Feeds Comments

Please give your valuable comments.