0

I have a string variable, selectors, holding class selectors: .class1,.class2,.class3

I'd like to selectively remove classes from that list depending on certain criteria (e.g. a user clicks button #2 and it removes .class2 from the list).

I'm having trouble coming up with the regular expression that allows for an optional comma at the front of the string to be removed. Here's what I've got:

var toRemove = '.class2';
var re = new RegExp(/\,\?/toRemove, 'gi');
newSelectors = selectors.replace(re, '');

I realize I'm probably screwing up trying to combine a pattern match with a variable, but I'm not entirely sure how to handle that.

daveycroqet
  • 2,667
  • 7
  • 35
  • 61
  • 1
    Both issues are very well-known, `,?` matches 1 or 0 commas, and `var re = new RegExp(",?"+toRemove.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), 'gi');` will do. – Wiktor Stribiżew Mar 17 '18 at 21:55
  • Damn, I was only missing the quotes and +? That's embarrassing... Thank you, sir. I had found that other thread but didn't feel it was applicable to my use-case. How very wrong I was. – daveycroqet Mar 17 '18 at 21:59

0 Answers0