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.
Strings are immuatable in javascript. You cannot change the contents of the current string object - ever. That's why all string methods that operate on the string return a new string object. So, your desired structure of:
where you want it to modify the current string object cannot be done.
You could make your own regular object that saves the state and then have methods that get or set that state like this:
Working example: http://jsfiddle.net/jfriend00/3urJF/