7/23/2007

Javascript string replacing function (2)

Previously I mentioned a string replacing function that, instead of building a string this way:

tag= '<' + tagname + ' style="background-color:'
+ bgcolor + ';color:' + color + '">' + text + '</' + tagname +'>'

allows for doing it this way:

tag0= '<___ style="background-color:___;color:___">___</___>'
tag1 = tag0._(tagname, bgcolor, color, text, tagname)

or this way :

tag00= '<[.tagname.] style="background-color:[.bgcolor.];'+
'color:[.color.]">[.txt.]</[.tagname.]>'

data = {tagname:'span', bgcolor:'#EEFFBB',color:'red',txt:'tag2'}
tag2 = tag00._(data)


After playing with the regular expression for a while, I come up with a short version :

String.prototype._=function(){
var i=-1, a= arguments
var t= typeof(a[0])=='string'
var rx = t?(/___/g):(/\[\.[A-Za-z0-9_]*\.\]/g)
var f = t?function(x){i++;return a[i]}
:function(x){return a[0][x.slice(2, -2)]||''}
return this.replace(rx,f)
}


To me it's amazing to see how such a task can be accomplished with such a neat code.

No comments: