I have tried to delete an item from a string divided with commas:
var str="this,is,unwanted,a,test";
- if I do a simple
str.replace('unwanted','');I end up with 2 commas - if I do a more complex
str.replace('unwanted','').replace(',,','');
It might work
But the problem comes when the str is like this:
var str="unwanted,this,is,a,test"; // or "...,unwanted"
However, I could do a ‘if char at [0 or str.length] == comma’, then remove it
But I really think this is not the way to go, it is absurd I need to do 2 replaces and 2 ifs to achieve what I want
I have heard that regex can do powerful stuff, but I simply can’t understand it no matter how hard I try
Important Notes:
- It should match after OR before (not both), or we will end with
“this,is,,a,test” - There are no spaces between commas
How about something less flaky than a regex for this sort of replacement?
jsFiddle.
However if you are convinced a regex is the best way…
(thanks Logan F. Smyth.)
jsFiddle.