PDA

View Full Version : String prototype extensions - post your best!


Choopernickel
04-27-2004, 07:30 PM
I couldn't find a single thread with the creme de la creme of String prototype extension methods, so I figured I'd start one. Here we go!

String.prototype.lTrim = function () {
return this.replace(/^\s+/gm, "");
}

String.prototype.rTrim = function () {
return this.replace(/\s+$/gm, "");
}

String.prototype.trim = function () {
return this.rTrim().lTrim();
}Obviously, this one's easy to understand. I'm using multi-line mode so as only to get rid of spaces and tabs before and after words. Single-line mode would replace any newline/carriage return characters as well.


String.prototype.capitalize = function () {
return this.replace(/\b[a-z]/g, function (str, n) { return str.toUpperCase(); });
}

String.prototype.toCamelCase = function () {
return this.replace(/\s[a-z]/g, function (str, n) { return str.toUpperCase(); });
}

String.prototype.unCamelCase = function () {
return this.replace(/[A-Z]/g, function (str, n) { return " " + str.toUpperCase(); });
}This is something I needed today, to turn a camelCased variable value into its Header Format. While I was at it, I wrote the un-do-er.

liorean
04-27-2004, 07:59 PM
The m flag in JavaScript regex is unsupported in ie5.0. Split at newlines and use trim on each string in the array, which you then merge, instead.

That is, if you want to support ie5 at all.

Choopernickel
04-27-2004, 11:01 PM
What's the marketshare on IE5 now? w3schools shows it's down to 10% and dropping every month -- and that's 5.0 combined with 5.5, so I doubt it's too many to worry about. Basically, what I do is code it to standards then get it working correctly in IE6 without breaking Firefox.

Is there a way, outside UA detection, to tell if a regex feature isn't supported in the current browser?

liorean
04-27-2004, 11:14 PM
Well, you could always try try{
/* use a feature that might cause errors */
}catch(e){
/* If it's unsupported, do this instead */
}However, I'm not sure that regex literals that are not recognised aren't considered syntax errors, which would mean that the try..catch statement doesn't work.

Caffeine
04-28-2004, 10:05 AM
What's the marketshare on IE5 now? w3schools shows it's down to 10% and dropping every month -- and that's 5.0 combined with 5.5, so I doubt it's too many to worry about.

I wouldn't trust the w3scools' stats, remember that most of their visitors likely are developers of some kind.. and most developers are better updated with what browsers that are around and so on.

thecounter.com has some stats of their own, which I belive reflects the average user better than w3schools, but I wouldn't trust their stats either, I'd think that if you merge the two sources you will get a better view of the situation.
http://www.w3schools.com/browsers/browsers_stats.asp
http://www.thecounter.com/stats/2004/March/browser.php


Sorry to go off-topic, but I think it's important to know that the w3schools stats most likely do not give a correct picture of the average webuser.

glenngv
04-28-2004, 11:34 AM
How about google stats (http://www.google.com/press/zeitgeist.html)?

glenngv
05-19-2004, 12:35 PM
Javascript's version of VBScript's Left (http://www.devguru.com/Technologies/vbscript/quickref/left.html) and Right (http://www.devguru.com/Technologies/vbscript/quickref/right.html) functions.

String.prototype.left = function(len){
return (len > this.length) ? this : this.substring(0, len);
}

String.prototype.right = function(len){
return (len > this.length) ? this : this.substring(this.length - len);
}

caldasgsm
07-23-2004, 11:18 PM
here is a bunch... pick one or else use all of them in this fast concatenation string class

var str = new CString('sample');
str.append(' text')
alert(str)

//contructor
function CString(sInitVal)
{
if(sInitVal)
{
this.sValue = sInitVal.toString();
this.length = this.sValue.length;
}
}
//private properties
CString.prototype.sValue = '';
CString.prototype.pElemBefore = new Array();
CString.prototype.pElemAfter = new Array();
CString.prototype.pArgs = new Array();
//public properties
CString.prototype.length = 0;

//private methods
CString.prototype.collectArgs = function(oArgs){this.pArgs = new Array();for(var i = 0; i < oArgs.length; i++)this.pArgs.push(oArgs[i]);}
CString.prototype.build = function(){if(this.pElemBefore.length==0 && this.pElemAfter.length==0)return;this.sValue = this.pElemBefore.reverse().join('') + this.sValue + this.pElemAfter.join('');this.length = this.sValue.length;this.pElemBefore = new Array();this.pElemAfter = new Array();}

//public methods
CString.prototype.valueOf = function(){this.build();return this.sValue.toString()}
CString.prototype.toString = function(){this.build();return this.sValue.toString()}

//new methods
CString.prototype.append = function(str){if(str instanceof Array)str = str.join();this.pElemAfter.push(str);return(this.length += str.length)}
CString.prototype.insert = function(str,index,deleteCount){if(str instanceof Array)str = str.join();if(!index||index==0){this.pElemBefore.push(str);}else{this.build();this.sValue = this.sValue.substr(0,(index?index:0)) + str + this.sValue.substr((index?index:0)+(deleteCount?deleteCount:0));}return (this.length += (str.length-(deleteCount?deleteCount:0)));}
CString.prototype.contains = function(str){this.build();return (this.sValue.indexOf(str)>=0);}
CString.prototype.remove = function(index,deleteCount){if(str instanceof Array)str = str.join('');this.build();this.sValue = this.sValue.substr(0,(index?index:0)) + this.sValue.substr((index?index:0)+(deleteCount?deleteCount:0));return (this.length -= deleteCount);}
CString.prototype.capitalize = function (){this.build();return new CString(this.sValue.replace(/\b[a-z]/g, function (str) { return str.toUpperCase(); }));}
CString.prototype.toCamelCase = function () {this.build();return new CString(this.sValue.replace(/\s[a-z]/g, function (str) { return str.toUpperCase(); }));}
CString.prototype.leftTrim = function () {this.build(); return new CString(this.sValue.replace(/^\s+/gm, ''));}
CString.prototype.rightTrim = function () {this.build();return new CString(this.sValue.replace(/\s+$/gm, ''));}
CString.prototype.trim = function () {this.build();return new CString(this.sValue.replace(/^\s+(.*)\s+$/gm, '$1'));}

//normal interface
CString.prototype.anchor = function(anchorString){this.build();return new CString(this.sValue.anchor(anchorString))}
CString.prototype.big = function(){this.build();return new CString(this.sValue.big())}
CString.prototype.blink = function(){this.build();return new CString(this.sValue.blink())}
CString.prototype.bold = function(){this.build();return new CString(this.sValue.bold())}
CString.prototype.fixed = function(){this.build();return new CString(this.sValue.fixed())}
CString.prototype.fontcolor = function(colorVal){this.build();return new CString(this.sValue.fontcolor(colorVal))}
CString.prototype.fontsize = function(intSize){this.build();return new CString(this.sValue.fontsize(intSize))}
CString.prototype.italics = function(){this.build();return new CString(this.sValue.italics())}
CString.prototype.link = function(linkstring){this.build();return new CString(this.sValue.link(linkstring))}
CString.prototype.small = function(){this.build();return new CString(this.sValue.small())}
CString.prototype.strike = function(){this.build();return new CString(this.sValue.strike())}
CString.prototype.sub = function(){this.build();return new CString(this.sValue.sub())}
CString.prototype.sup = function(){this.build();return new CString(this.sValue.sup())}
CString.prototype.toLocaleLowerCase = function(){this.build();return new CString(this.sValue.toLocaleLowerCase())}
CString.prototype.toLocaleUpperCase = function(){this.build();return new CString(this.sValue.toLocaleUpperCase())}
CString.prototype.toLowerCase = function(){this.build();return new CString(this.sValue.toLowerCase())}
CString.prototype.toUpperCase = function(){this.build();return new CString(this.sValue.toUpperCase())}

CString.prototype.localeCompare = function(stringExp){this.build();return this.sValue.localeCompare(stringExp)}
CString.prototype.charAt = function(index){this.build();return new CString(this.sValue.charAt(index))}
CString.prototype.charCodeAt = function(index){this.build();return this.sValue.charCodeAt(index)}
CString.prototype.indexOf = function(subString, startIndex){this.build();return this.sValue.indexOf(subString, startIndex)}
CString.prototype.lastIndexOf = function(subString, startIndex){this.build();return this.sValue.lastIndexOf(subString, startIndex)}
CString.prototype.match = function(rgExp){this.build();return this.sValue.match(rgExp)}
CString.prototype.replace = function(rgExp, replaceText){this.build();return new CString(this.sValue.replace(rgExp, replaceText))}
CString.prototype.search = function(rgExp){this.build();return this.sValue.search(rgExp)}
CString.prototype.slice = function(start,end){this.build();return new CString(this.sValue.slice(start,end))}
CString.prototype.split = function(separator, limit){this.build();return this.sValue.split(separator, limit)}
CString.prototype.substr = function(start, end){this.build();return new CString(this.sValue.substr(start, end))}
CString.prototype.substring = function(start, end){this.build();return new CString(this.sValue.substring(start, end))}
CString.prototype.fromCharCode = function(CharCode){this.collectArgs(arguments);var pChars = new Array();for(var i = 0;i < this.pArgs.length;i++)pChars.push(String.fromCharCode(this.pArgs[i]));return new CString(pChars.join(''));}
CString.prototype.concat = function(string){this.collectArgs(arguments);this.build();return new CString(this.sValue +this.pArgs.join(''));}

cagrET
07-23-2004, 11:24 PM
I've recently written two String funcs that are quite useful for me:

/*
* Replace ? tokens with variables passed as arguments in a string.
* When you are joining many strings with variables, this is a good way to keep the code clean
* Examples:
* var s = '<div id="'+id+'" class="'+className+'">'+innerText+'</div>';
* var s = '<div id="?" class="?">?</div>'.format(id, className, innerText);
*/
String.prototype.format = function() {
if (!arguments.length) { throw "String.format() failed, no arguments passed, this = "+this; }
var tokens = this.split("?");
if (arguments.length != (tokens.length - 1)) { throw "String.format() failed, tokens != arguments, this = "+this; }
var s = tokens[0];
for (var i = 0; i < arguments.length; ++i) {
s += (arguments[i] + tokens[i + 1]);
}
return s;
};

/* Repeat string n times */
String.prototype.repeat = function(n) {
var ret = "";
for (var i = 0; i < n; ++i) {
ret += this;
}
return ret;
};


More you can download here: http://gosu.pl/download/String.js
And unit tests: http://gosu.pl/download/String.html