Monday, December 5, 2011

javascript startsWith() and endsWith()

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


Javascript function endsWith
String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}


Usage:
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…

 
Ref: here

No comments: