Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

trim(), startsWith() and endsWith() in JavaScript?

Strings

trim(), startsWith() and endsWith() in JavaScript?

by  Jay1Roy  Posted    (Edited  )
All programmers who use JavaScript at some stage get frustrated searching for some standard functions that are simply not built into JavaScript! Also if you manage to write your own version for it, the call isn't as neat as the standard ones.

eg. calling the in-built [tt]substr()[/tt] function would look something like [tt]myVar.substr(x, y)[/tt] but if you wrote your own version (may be function [tt]substr2(str, x, y))[/tt] you'll have to call it as

Code:
myVar = substr2(myVar, x, y); //Your function
myVar = myVar.substr(x, y); //built-in function

Not so elegant is it?
Well, here is a way you could BIND your functions to the data type and call them like in-built functionsà here's how:

Trim function, trims all leading and trailing spaces:
Code:
String.prototype.trim = function(){return 
(this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))}

startsWith to check if a string starts with a particular character sequecnce:
Code:
String.prototype.startsWith = function(str) 
{return (this.match("^"+str)==str)}

endsWith to check if a string ends with a particular character sequecnce:
Code:
String.prototype.endsWith = function(str) 
{return (this.match(str+"$")==str)}

All these functions once loaded will behave as built-in JavaScript functions. Here are few examples:
Code:
var myStr = ô  Earth is a beautiful planet  ö;
var myStr2 = myStr.trim();  
//==ôEarth is a beautiful planetö;

if (myStr2.startsWith(ôEarthö)) // returns TRUE

if (myStr2.endsWith(ôplanetö)) // returns TRUE

if (myStr.startsWith(ôEarthö)) 
// returns FALSE due to the leading spacesà

if (myStr.endsWith(ôplanetö)) 
// returns FALSE due to trailing spacesà
Summary: Any function you think will be needed on a data type level can be implemented in this wayà you donÆt always need to use regular expressions for this but it does make it really compact.

Let me know if this was useful![thumbsup2]

Enjoy scriptingà[noevil]
Jay
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top