Click here to Skip to main content
15,881,812 members
Articles / Web Development / ASP.NET
Tip/Trick

Create Trim function in javascript

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
13 Nov 2010CPOL 21.3K   5   2
You can define a trim function which trims leading and trailing space in JavaScript by using any one of the following ways:

way 1:
String.prototype.trim = function() {  return this.replace(/^\s+|\s+$/g, '');  }


way 2:
function trim()
{
 return this.replace(/^\s+|\s+$/g, ''); 
}


The following function shows how to use the trim function

function temp()
{

 var str='    maninder     ';
 alert(str.trim());
}


You will see 'maninder' in the alert box. All the leading and trailing space are trimmed. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralPlease rate this if it helped you Pin
shankeyshankey2-Nov-10 4:42
shankeyshankey2-Nov-10 4:42 
General\s is whitespace Pin
jsc428-Nov-10 22:59
professionaljsc428-Nov-10 22:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.