Share this page 

trim(), endWith() or startsWith() on a StringTag(s): Language


First you declare some new prototypes on the String object.
String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}


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


String.prototype.trim = function(){return
(this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))}
and then these new methods are available to process the String.
var s = "  Real's HowTo  ";
var sTrimmed = s.trim();  //  =="Real's HowTo"

if (sTrimmed.startsWith("Real")) // returns TRUE

if (sTrimmed.endsWith("HowTo")) // returns TRUE

if (s.startsWith("Real")) // returns FALSE due to the leading spaces

if (s.endsWith("HowTo"))  // returns FALSE due to trailing spaces