Top 10 JavaScript String.prototype Extensions
July 10th, 2007 by Ivan Uzunov
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={’&’:'&’,'<’:'<’,'>’:'>’,'"’:'"’},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={’<’:'<’,'>’:'>’,'&’:'&’,'"’:'"’},t=this; for(i in e) t=t.replace(new RegExp(i,’g'),e[i]); return t }//test unescHtml
test = ‘testing <b>unescHtml</b>’;
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()); } }JavaScript, String.prototype, Top 10//test endsWith
test = ‘Can you find me?’;
document.write (test.endsWith(’Me?’, true));




[…] está bien extenderlos para conseguir aumentar las ya interesantes funcionalidades. Compártelo # « De cena con Yusef HassanMontero […]
[…] Top 10 JavaScript String.prototype Extensions […]
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
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;
}
Good extensions.
But to escape the string, you also try my htmlEntities function.
Nice little set of extensions ( can’t believe JavaScript didnt already have a TRIM() extension! lol)
[…] 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. […]
[…] 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. […]
[…] 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?
(btw, in my last comment I asked the poster to make use of the English language)
[…] 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. […]
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…
[…] 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) […]
[…] Top 10 JavaScript String.prototype Extensions (tags: JavaScript) […]
what about String.reverse()?
String.prototype.reverse = function(){
return this.split(”").reverse().join(”");
};
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.
[…] JavaScript String.prototype Extensions […]
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…
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.
I do not see any reason for these extensions when JavaScript supports Regular Expressions which can do all the above.
[…] Ivan Uzunov Blog » Blog Archive » Top 10 JavaScript String.prototype Extensions (tags: javascript prototype string code tips) […]
[…] Top 10 JavaScript String.prototype Extensions とっても便?なJS文字?拡張。 […]
Andrew, don’t worry about the split with trim. Each element of the returned array is trimmed
[…] Ivan Uzunov Blog » Blog Archive » Top 10 JavaScript String.prototype Extensions (tags: Javascript Extension Programming Tips String) […]
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
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’);
[…] Extendiendo la clase String con Prototype. […]
[…] con utilidades para extender la clase String de javascript. Read More Post aComment […]
Why not add String.prototype.md5()
[…] top 10 JavaScript string.prototype extensions […]
[…] 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. […]