user1022373
user1022373

Reputation:

Regex: match word (but delete commas after OR before)

I have tried to delete an item from a string divided with commas:

var str="this,is,unwanted,a,test";

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:

Upvotes: 2

Views: 445

Answers (2)

alex
alex

Reputation: 490263

How about something less flaky than a regex for this sort of replacement?

str = str
     .split(',')
     .filter(function(token) { return token !== 'unwanted' })
     .join(',');

jsFiddle.

However if you are convinced a regex is the best way...

str = str.replace(/(^|,)?unwanted(,|$)?/g, function(all, leading, trailing) {
    return leading && trailing ? ',' : '';
});

(thanks Logan F. Smyth.)

jsFiddle.

Upvotes: 2

loganfsmyth
loganfsmyth

Reputation: 161457

Since Alex hasn't fixed this in his solution, I wanted to get a fully functional version up somewhere.

var unwanted = 'unwanted';
var regex = new RegExp('(^|,)' + unwanted + '(,|$)', 'g');
str = str.replace(regex, function(a, pre, suf) {
  return pre && suf ? ',' : '';
});

The only thing to be careful of when dynamically building a regex, is that the 'unwanted' variable can't have anything in it that could be interpretted as a regex pattern.

There are way easier ways to parse this though, as Alex mentioned. Don't resort to regular expressions unless you have to.

Upvotes: 1

Related Questions