Simple example how-to extend JavaScript built-in methods

Let say you want to replace all spaces in string by dashes,
of course you can implement distinct function that does it:



 function ReplaceByDashes(string){
    return string.replace(/\s/g,'-');
 }

 // run it
 var string = "Hello my beautiful world!";
 string=ReplaceByDashes(string);
 alert(string); 



However, we can add our custom method to string object that already built-in in JavaScript:



  if(typeof String.prototype.rbd==='undefined'){ // we have to check if someone hasn't added it already
     String.prototype.rbd = function(){
        return this.replace(/\s/g,'-');
     }
  }

 // run it

 var string = "Hello my beautiful world!";
 string=string.rbd();
 alert(string); 



Some useful example, capitalize first letter of string



String.prototype.ucFirst = function () {
  return (this.substr(0,1).toUpperCase() + this.substr(1,this.length));
}

  • +2
  • April 28, 2010, 10:08pm
  • EvgenyM

Comments (3)

RSS Collapse / Expand
+
+1
Useful case, thanks!
avatar

tapin13

  • April 29, 2010, 1:33am
+
+1
Thanks, interesting.
Waiting for more complicated stuff.

What about Ruby?
avatar

paker

  • April 29, 2010, 4:17am
+
0
tnx for comments, I will post smth about ruby soon, I'm playing now with cherokee webserver + python
avatar

t0lkman

  • April 29, 2010, 5:47am

Only registered and authorized users can leave comments. Login or Register