Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here


trim(), startsWith() and endsWith() in JavaScript? by Jay1Roy
Posted: 17 Apr 07 (Edited 17 Apr 07)

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 substr() function would look something like myVar.substr(x, y) but if you wrote your own version (may be function substr2(str, x, y)) you'll have to call it as


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:


String.prototype.trim = function(){return
(this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))}

startsWith to check if a string starts with a particular character sequecnce:


String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}

endsWith to check if a string ends with a particular character sequecnce:


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:


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

Back to Javascript FAQ Index
Back to Javascript Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close