Feed on
Posts
Comments

This is the list of mine top 10 JavaScript String.prototype extensions. If you want to you can post yours bellow.

This extension adds trim() function:

String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,'’); }

//test trim
test = ‘ testing trim ‘;
document.write (’"’ + test.trim() + ‘"’);

This extension splits the string by given separator and returns an array with trimmed  items. It uses the trim() extension above:

String.prototype.splitrim = function(t){ return this.trim().split(new RegExp(’\\s*’+t+’\\s*’)) }

//test splitrim
test = ‘ testing   , splitrim ‘;
var arr = test.splitrim(’,');
document.write (’"’ + arr[0] + ‘"’);
document.write (’"’ + arr[1] + ‘"’);

This extension escapes HTML in the string:

String.prototype.escHtml = function(){ var i,e={’&’:'&amp;’,'<’:'&lt;’,'>’:'&gt;’,'"’:'&quot;’},t=this; for(i in e) t=t.replace(new RegExp(i,’g'),e[i]); return t }

//test escHtml
test = ‘testing <b>escHtml</b>’;
document.write (test.escHtml());

This extension unescapes HTML in the string:

String.prototype.unescHtml = function(){ var i,e={’&lt;’:'<’,'&gt;’:'>’,'&amp;’:'&’,'&quot;’:'"’},t=this; for(i in e) t=t.replace(new RegExp(i,’g'),e[i]); return t }

//test unescHtml
test = ‘testing &lt;b&gt;unescHtml&lt;/b&gt;’;
document.write (test.unescHtml());

This extension URL encodes the string:

String.prototype.urlEncode = function(){ return encodeURIComponent(this); }

//test urlEncode
test = ‘http://www.gmail.com’;
document.write (test.urlEncode());

This extension checks if the string is a valid email address:

String.prototype.isEmail = function () { var rx = new RegExp("\\w+([-+.\’]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"); var matches = rx.exec(this); return (matches != null && this == matches[0]); }

//test isEmail
test = ‘test@gmail.com’;
document.write (test.isEmail());

This extension checks if the string is a valid URL address:

String.prototype.isURL = function () { var rx = new RegExp("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-\\+ ./?%:&=#\\[\\]]*)?"); var matches = rx.exec(this); return (matches != null && this == matches[0]); }

//test isURL
test = ‘http://www.gmail.com’;
document.write (test.isURL());

This extension checks if the string contains the passed as parameter value:

String.prototype.contains = function(t) { return this.indexOf(t) >= 0 ? true : false; }

//test contains
test = ‘Can you find me?’;
document.write (test.contains(’find me’));

This extension checks if the string begins with the passed as parameter value. The second parameter is for ignore case:

String.prototype.beginsWith = function(t, i) { if (i==false) { return (t == this.substring(0, t.length)); } else { return (t.toLowerCase() == this.substring(0, t.length).toLowerCase()); } }

//test beginsWith
test = ‘Can you find me?’;
document.write (test.beginsWith(’can you’, true));

This extension checks if the string ends with the passed as parameter value. The second parameter is for ignore case:

String.prototype.endsWith = function(t, i) { if (i==false) { return (t == this.substring(this.length - t.length)); } else { return (t.toLowerCase() == this.substring(this.length - t.length).toLowerCase()); } }

//test endsWith
test = ‘Can you find me?’;
document.write (test.endsWith(’Me?’, true));

, ,
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • dzone
  • Netscape
  • digg
  • YahooMyWeb
  • Technorati

31 Responses to “Top 10 JavaScript String.prototype Extensions”

  1. […] está bien extenderlos para conseguir aumentar las ya interesantes funcionalidades. Compártelo # « De cena con Yusef HassanMontero […]

  2. […] Top 10 JavaScript String.prototype Extensions […]

  3. on 10 Jul 2007 at 4:46 pm Dre

    A while ago i ran into a encoding problem between IE (duh) and my db. Somehow it would assume it had another code page then it normally has and the text in the site would be all mangeld up. I found this method on the web in another language and ported it to javascript. I unforonaly don’t know the orginal site anymore =(. It takes one argument wich will tell it to add a UTF8 header or not.

    String.prototype.toUTF8 = function(addHeader){
    // Because we are creating a UTF-8 string we need to add the UTF-8 header aswell
    var outputString = addHeader === true ?
    (String.fromCharCode(0xEF) + String.fromCharCode(0xBB) + String.fromCharCode(0xBF)) : “”;
    var charCode = 0×00;

    for(var n = 0; n = 0×00000080 && charCode = 0×000007FF && charCode = 0×0000FFFF && charCode = 0×001FFFFF && charCode = 0×03FFFFFF && charCode

  4. on 10 Jul 2007 at 4:49 pm Dre

    Your comment system seems to hate me…

    String.prototype.toUTF8 = function(addHeader){
    // Because we are creating a UTF-8 string we need to add the UTF-8 header aswell
    var outputString = addHeader === true ?
    (String.fromCharCode(0xEF) + String.fromCharCode(0xBB) + String.fromCharCode(0xBF)) : “”;
    var charCode = 0×00;

    for(var n = 0; n < this.length; n++){
    charCode = this.charCodeAt(n);

    if(charCode < 0×00000080){
    outputString += String.fromCharCode(charCode);
    continue;
    }else if(charCode >= 0×00000080 && charCode <= 0×000007FF){
    outputString += String.fromCharCode(192 + (charCode / 64));
    outputString += String.fromCharCode(128 + (charCode % 64));
    continue;
    }else if(charCode >= 0×000007FF && charCode <= 0×0000FFFF){
    outputString += String.fromCharCode(224 + (charCode / 4096));
    outputString += String.fromCharCode(128 + ((charCode / 64) % 64));
    outputString += String.fromCharCode(128 + (charCode % 64));
    continue;
    }else if(charCode >= 0×0000FFFF && charCode <= 0×001FFFFF){
    outputString += String.fromCharCode(240 + (charCode / 262144));
    outputString += String.fromCharCode(128 + ((charCode / 4096) % 64));
    outputString += String.fromCharCode(128 + ((charCode / 64) % 64));
    outputString += String.fromCharCode(128 + (charCode % 64));
    continue;
    }else if(charCode >= 0×001FFFFF && charCode <= 0×03FFFFFF){
    outputString += String.fromCharCode(248 + (charCode / 16777216));
    outputString += String.fromCharCode(128 + ((charCode / 262144) % 64));
    outputString += String.fromCharCode(128 + ((charCode / 4096) % 64));
    outputString += String.fromCharCode(128 + ((charCode % 64) % 64));
    outputString += String.fromCharCode(128 + (charCode % 64));
    continue;
    }else if(charCode >= 0×03FFFFFF && charCode <= 0×7FFFFFFF){
    outputString += String.fromCharCode(252 + (charCode / 1073741824));
    outputString += String.fromCharCode(128 + ((charCode / 16777216) % 64));
    outputString += String.fromCharCode(128 + ((charCode / 262144) % 64));
    outputString += String.fromCharCode(128 + ((charCode / 4096) % 64));
    outputString += String.fromCharCode(128 + ((charCode / 64) % 64));
    outputString += String.fromCharCode(128 + (charCode % 64));
    continue;
    }else{
    continue;
    }
    }

    return outputString;
    }

  5. on 10 Jul 2007 at 4:57 pm Micox

    Good extensions.
    But to escape the string, you also try my htmlEntities function.

  6. on 10 Jul 2007 at 8:16 pm steve

    Nice little set of extensions ( can’t believe JavaScript didnt already have a TRIM() extension! lol)

  7. […] Existen métodos que no trae Javascript para la operación con cadenas y que nos son muy útiles a la hora de programar, pues bien podemos hacer uso de Prototype para agregarles estos métodos al objeto String a continuación se listan 10 Métodos. […]

  8. […] Existen métodos que no trae Javascript para la operación con cadenas y que nos son muy útiles a la hora de programar, pues bien podemos hacer uso de Prototype para agregarles estos métodos al objeto String a continuación se listan 10 Métodos. […]

  9. on 11 Jul 2007 at 2:05 pm henk

    […] Existen métodos que no trae Javascript para la operación con cadenas y que nos son muy útiles a la hora de programar, pues bien podemos hacer uso de Prototype para agregarles estos métodos al objeto String a continuación se listan 10 Métodos. […]

    Op het internet is het toch wel handig om een reply in het engels te geven, zeker als het een engelse blog posting betreft. Als iedereen een beetje z’n eigen taaltje gaat lullen kunnen we net zo goed het internet opheffen en allemaal een lokaal (landelijk) netwerk gaan gebruiken, toch?

  10. on 11 Jul 2007 at 2:06 pm henk

    (btw, in my last comment I asked the poster to make use of the English language)

  11. […] Existen métodos que no trae Javascript para la operación con cadenas y que nos son muy útiles a la hora de programar, pues bien podemos hacer uso de Prototype para agregarles estos métodos al objeto String a continuación se listan 10 Métodos. […]

  12. on 12 Jul 2007 at 1:53 am todo.noticia.es

    10 Métodos Útiles para Extender el Objeto String en Javascript

    Existen métodos que no trae Javascript para la operación con cadenas y que nos son muy útiles a la hora de programar, pues bien podemos hacer uso de Prototype para agregarles estos métodos al objeto String a continuaci&oacut…

  13. […] Top 10 JavaScript String.prototype Extensions useful string prototype functions for js. from http://www.ivanuzunov.net/top-10-javascript-stringprototype-extensions/ (tags: string prototype programming snippets code webdesign webdev javascript) […]

  14. on 12 Jul 2007 at 2:04 pm All in a days work…

    […] Top 10 JavaScript String.prototype Extensions (tags: JavaScript) […]

  15. on 12 Jul 2007 at 5:10 pm gonchuki

    what about String.reverse()?

    String.prototype.reverse = function(){
    return this.split(”").reverse().join(”");
    };

  16. on 13 Jul 2007 at 3:56 pm Matt

    I’d change

    String.prototype.contains = function(t) { return this.indexOf(t) >= 0 ? true : false; }

    to

    String.prototype.contains = function(t) { return this.indexOf(t) >= 0; }

    >= 0 will return true or false already, no need to check its return value and again return true or false.

  17. on 16 Jul 2007 at 10:21 am dev2 - webfejlesztés » Csemegék

    […] JavaScript String.prototype Extensions […]

  18. on 17 Jul 2007 at 3:47 pm lm

    A small improvement:

    String.prototype.contains = function(t) { return this.indexOf(t) >= 0 ? true : false; }

    ==>

    String.prototype.contains = function(t) { return this.indexOf(t) >= 0; }

    @gonchuki: I’ve always wondered why string reverse is so popular that it’s found in each and every textbook. I’ve been programming for 20 years now and never, ever needed to reverse a string except in one job interview. Maybe you can tell me… ;-)

  19. on 17 Jul 2007 at 4:09 pm Andrew

    I’m a big fan of trim and split (with trim), but it’d be perhaps a bit more useful if trim was applied to each of the elements after the split.

    I’m also a bit worried about the use of regular expressions for such simple search and replace as required by the html escape. Compiling regular expressions is going to eventually bite you, whereas using string’s replace with a string (and not a regex) will be far superior.

  20. on 17 Jul 2007 at 7:52 pm sonic

    I do not see any reason for these extensions when JavaScript supports Regular Expressions which can do all the above.

  21. on 18 Jul 2007 at 2:25 am links for 2007-07-17 « toonz

    […] Ivan Uzunov Blog » Blog Archive » Top 10 JavaScript String.prototype Extensions (tags: javascript prototype string code tips) […]

  22. […] Top 10 JavaScript String.prototype Extensions とっても便?なJS文字?拡張。 […]

  23. on 18 Jul 2007 at 11:34 am Ivan Uzunov

    Andrew, don’t worry about the split with trim. Each element of the returned array is trimmed :)

  24. on 18 Jul 2007 at 5:00 pm links for 2007-07-18 « 玻璃鏡

    […] Ivan Uzunov Blog » Blog Archive » Top 10 JavaScript String.prototype Extensions (tags: Javascript Extension Programming Tips String) […]

  25. on 24 Jul 2007 at 6:00 pm Nathan Friedly

    I’d consider replacing that trim function. It’s certainly not the slowest around, but there are other functions available that can be 50-100 times faster for long strings. See http://blog.stevenlevithan.com/archives/faster-trim-javascript

  26. on 27 Jul 2007 at 12:46 am Dave

    An extension with prototype.js I wrote…

    Object.extend(String, {
    format: function(format) {
    var args = (Array.from(arguments)).slice(1);
    return format.replace(/\{(\d+)\}/g, function(pat, index) {
    return args[ Number(index) ].toString();
    });
    }
    });

    var x = String.format(’Hi {0}.’, ‘dave’);

  27. on 30 Jul 2007 at 8:51 am Utilidades Javascript

    […] Extendiendo la clase String con Prototype. […]

  28. […] con utilidades para extender la clase String de javascript.     Read More    Post aComment […]

  29. on 11 Aug 2007 at 3:36 pm jiang kuan

    Why not add String.prototype.md5()

  30. on 15 Aug 2007 at 10:07 pm Tiernans Comms Closet : Random Links

    […] top 10 JavaScript string.prototype extensions […]

  31. […] Today I found out that you can extend the JavaScript String object with the String.prototype extensions (standard part of the JavaScript language). So when you define a function like: String.prototype.trim = function(){ } Then you can just use it like: test.trim() While not being very spectucular, it’s still pretty neat. When you are dealing with forms that require a lot of checks, than this baby can come to hand. Here the blog entry that pointed me to this. […]

Trackback URI | Comments RSS

Leave a Reply

This is a captcha-picture. It is used to prevent mass-access by robots. (see: www.captcha.net)

You must read and type the 5 chars within 0..9 and A..F, and submit the form.

  

Oh no, I cannot read this. Please, generate a