Removing a simple pattern from a string!
-
i folks, Consider the following JavaScript function: function removeParam(str, name) { var rgx = new RegExp('(' + name + '=\\w*)|(' + name + '=\\w*;)'); rgx.global = true; rgx.ignoreCase = true; var matches = rgx.exec(str); if(matches == null) return str; var i; for(i = 0; i < matches.length; i++) str = str.replace(matches[i], ''); return str; } and the following call: var cookie = 'vid=39; vid=38; ASPNETSESSION=WHATEVER; vid=39'; alert(removeParam(cookie, 'vid')); I actually would like to remove "vid=(whatever number)" from the above string, so that it results in the following string: ASPNETSESSION=WHATEVER would someone please helps me to fix the problem? I've got no idea what's wrong with the above pattern I've written. Thank you for your time. Mehdi Mousavi - Software Architect [ http://mehdi.biz ]
-
i folks, Consider the following JavaScript function: function removeParam(str, name) { var rgx = new RegExp('(' + name + '=\\w*)|(' + name + '=\\w*;)'); rgx.global = true; rgx.ignoreCase = true; var matches = rgx.exec(str); if(matches == null) return str; var i; for(i = 0; i < matches.length; i++) str = str.replace(matches[i], ''); return str; } and the following call: var cookie = 'vid=39; vid=38; ASPNETSESSION=WHATEVER; vid=39'; alert(removeParam(cookie, 'vid')); I actually would like to remove "vid=(whatever number)" from the above string, so that it results in the following string: ASPNETSESSION=WHATEVER would someone please helps me to fix the problem? I've got no idea what's wrong with the above pattern I've written. Thank you for your time. Mehdi Mousavi - Software Architect [ http://mehdi.biz ]
Perhaps you should mention what the problem is? It would greatly simplify fixing it... ;) I don't think that your replace is working the way you think. At least you should skip the first item in the array, as it contains the entire matched string, not a matched group. Why don't you just use the RegExp object in a replace?
function removeParam(str, name) { var rgx = new RegExp('(^|; )' + name + '=\\w*(?:; )?'); rgx.global = true; rgx.ignoreCase = true; return str.replace(rgx, '$1'); }
I simplified the expression a bit, and made it aware of the beginning of the string or the separator before the name, so that it doesn't mess up other values. Otherwise removing the "on" property from "on=42; ASPNETSESSION=WHATEVER" would result in "ASPNETSESSI". Reservation for typos, though. The code is not tested. --- b { font-weight: normal; }