![]() |
Trim function JavaScript/JScript
On 1st December, 2006
|
|
Trim function JavaScript/JScript
Recent Articles
Similar Articles
Code: JavaScript
Code: JavaScript
|
|
|
#2 |
|
Newbie Member
Join Date: May 2007
Location: pagalkhana
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Rep Power: 0 ![]() |
Re: Trim function JavaScript/JScript
great
|
|
|
|
|
|
#3 |
|
Go4Expert Member
Join Date: Oct 2007
Posts: 43
Thanks: 0
Thanked 1 Time in 1 Post
Rep Power: 0 ![]() |
Re: Trim function JavaScript/JScript
Good use of regular expressions, we wish there was a simpler method like vbscript where in we can just use the function trim.
|
|
|
|
|
|
#4 |
|
Newbie Member
Join Date: Mar 2009
Location: Melbourne, Australia
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Rep Power: 0 ![]() |
Re: Trim function JavaScript/JScript
Hi Pradeep, Nice solution. Although it could be extended nicely so it works natively in Javascript. JS provides a way to create prototype functions easily. Here is the code: Code:
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }
|
|
|
|
|
|
#5 |
|
Banned
Join Date: Jun 2009
Posts: 58
Thanks: 0
Thanked 0 Times in 0 Posts
Rep Power: 0 ![]() |
Re: Trim function JavaScript/JScript
Use the code below to make trim a method of all Strings. These are useful to place in a global Javascript file included by all your pages. Code:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
return this.replace(/\s+$/,"");
}
// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+myString.trim()+"*");
alert("*"+myString.ltrim()+"*");
alert("*"+myString.rtrim()+"*");
Code:
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
return stringToTrim.replace(/\s+$/,"");
}
// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+trim(myString)+"*");
alert("*"+ltrim(myString)+"*");
alert("*"+rtrim(myString)+"*");
|
|
|
|
|
|
#6 |
|
Team Leader
![]() |
Re: Trim function JavaScript/JScript
Nice one gkumar
__________________
Vote for the Most Entertaining Member of 2008 To err is human,to detect is divine! |
|
|
|
![]() |
|
| Currently Active Users Reading This Article: 1 (0 members and 1 guests) | |
| Article Tools | Search this Article |
| Display Modes | |
| Bookmarks | |
|
|
|
|||||||||||||||||||||||||||||||||||||