1

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"]';
2
  • 1
    What about these: values['aaa','bbb','ccc'], values["aaa", "bbb" ,"ccc"], values["bbb"], values['"aaa","bbb","ccc"'] ? Commented Dec 22, 2014 at 6:48
  • Thanks Kobi, for my sample it will only use double quotes but values["bbb"] is valid. Commented Dec 22, 2014 at 6:51

4 Answers 4

3

You need to use alternation operator |.

String you want to replace is at the middle

> var strToReplace = 'bbb';
undefined
> var str = 'values["aaa","bbb","ccc"]';
undefined
> var replaceRegexp = new RegExp('"'+ strToReplace +'",|,"'+ strToReplace +'"', 'g');
undefined
> str.replace(replaceRegexp,'');
'values["aaa","ccc"]'

String you want to replace is at the last

> var str = 'values["aaa","ccc","bbb"]';
undefined
> var strToReplace = 'bbb';
undefined
> var replaceRegexp = new RegExp('"'+ strToReplace +'",|,"'+ strToReplace +'"', 'g');
undefined
> str.replace(replaceRegexp,'');
'values["aaa","ccc"]'

String you want to replace is at the first

> var strToReplace = 'bbb';
undefined
> var str = 'values["bbb","aaa","ccc"]';
undefined
> var replaceRegexp = new RegExp('"'+ strToReplace +'",|,"'+ strToReplace +'"', 'g');
undefined
> str.replace(replaceRegexp,'');
'values["aaa","ccc"]'

| called alternation or logical or operator. But the logical OR operator is a must needed one.

At first, the regex engine would try to match all the chars using the pattern before the | symbol. After that, it tries to match the remaining characters (in this case) using the pattern which was next to the | operator.

So the first part of the above regex "bbb", matches all the bbb, strings but it fails to match the last bbb because it isn't have a following comma. Then the next pattern ",bbb"comes into attack and matches the last ,bbb string.

OR

YOu could use the below regex if you want to remove "bbb" if the list has only "bbb"

> var str = 'values["bbb"]';
undefined
> var replaceRegexp = new RegExp('"'+ strToReplace +'",|,?"'+ strToReplace +'"', 'g');
undefined
> str.replace(replaceRegexp,'');
'values[]'
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks. Hitting myself in the head now. how could I forget about |. The positive assertion is new to me. I don't think it is really needed but can you explain this further. Thanks
Add a 'g' flag to make it replace multiple instances and remove the unecessary lookahead and this is the correct answer.
Kobi just pointed out in the commment a valid scenario which is values["bbb"] but this does not cover it.
I think @Makaze post was more on the spot but he deleted it.
Mine didn't cover a case where bbb was in the middle. I'll go ahead and make one that catches all of the cases then.
|
2
"bbb",|,?"bbb"

You can try something like this which will fulfll all conditions.See demo.

https://regex101.com/r/vN3sH3/40

2 Comments

Thanks. I think this one covers most of the scenarios so far.
@DRTauli is there anyone left?
1

This is optimimal in my opinion.

var strToReplace = 'bbb',
  re = new RegExp('(,?)"' + strToReplace + '"(,?)', 'g'),
  str = 'values["bbb","aaa","ccc","bbb","ccc","aaa","bbb"]';

str = str.replace(re, function(match, sub1, sub2) {
    if (!sub1.length || !sub2.length) {
        return '';
    } else {
        return ',';
    }
});

document.getElementById('result').textContent = str;
console.log(str);
<div id="result"></div>

Comments

0

This is the regex used in my javascript code and it works for me, given finding string is "findme":

/^findme,|,findme$|,findme(?=,)/

And code snippet like this:

var find = form1.find.value;
var source = form1.source.value;
var regex = new RegExp("^"+find+",|,"+find+"$|,"+find+"(?=,)");
var result = source.replace(regex, "");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.