I want to remove a string inside a comma delimited string and I want to do this via regex.
var strToReplace = 'bbb';
var str = 'values["aaa","bbb","ccc"]';
The problem I encountered was the commas. Replacing only the desired string leaves the commas behind so I added removing also the following comma if present.
var replaceRegexp = new RegExp('"'+ strToReplace +'",?');
str = str.replace(replaceRegexp,'');
However it leaves a trailing comma if it was the last item. Adding it to the front will have the same problem if removing the first item and adding to both sides will remove the commas when removing from the the middle items.
I just added another replace string to remove the trailing one after removing the item.
str = str.replace('",]','"]');
Can someone point me to a more elegant way to handle this in just one regExp. Thanks
EDIT:
var str = 'values["aaa","bbb","ccc"]';
var str = 'values["bbb"]';
var str = 'values["aaa","bbb","ccc","bbb"]';
values['aaa','bbb','ccc'],values["aaa", "bbb" ,"ccc"],values["bbb"],values['"aaa","bbb","ccc"']?