I found my self quite often parsing values from the so called Name Value Lists in JavaScript.
I used a self made function which did the job pretty well, however I decided to experiment with the prototype property. It seems to work, however I find the second function "nvlSet" kind of "ugly".
Do you think it is?.. if so, how do you think it can turn into a more "elegant" way to do the job.
if(!String.prototype.nvlGet) {
String.prototype.nvlGet = function(nme,def){
return((rem0=new RegExp('(\\b|,)' + nme + '=([^\\b][^,]*)').exec(this)) ? rem0[2] : def);
}
}
if(!String.prototype.nvlSet) {
String.prototype.nvlSet = function(nme,val){
var re0=new RegExp('(\\b' + nme + '=[^\\b][^,]*)');
if(re0.test(this)) return(this.replace(re0,nme + "=" + val));
re0.compile('(,' + nme + '=[^\\b][^,]*)');
return(this.replace(re0,',' + nme + "=" + val));
}
}
var lst='firstName=John,lastName=Smith,department=Sales';
alert(lst.nvlGet('firstName')); // John
alert(lst.nvlGet('surName','none')); // none
lst=lst.nvlSet('department','Research');
alert(lst.nvlGet('department','unknown')); // Research
alert(lst); // firstName=John,lastName=Smith,department=Research
Also, I would like to avoid the "double assignation" like in here:
lst=lst.nvlSet('department','Research');
To something like this:
lst.nvlSet('department','Research');
However I could not find a way to do it.