Abdullah
Abdullah

Reputation: 351

JavaScript Regex Match Value + Comma and Replace with Empty or space

I am using javascript .replace function to replace match content/pattern but problem it replace match content but didn't get the comma associate with, Like:

i have var a = 'gJDjOw0ern8,-4oCq2Vw4GQ,fjsrhmUhK60';
and b = 'gJDjOw0ern8,-4oCq2Vw4GQ';

and i want to remove only match values, like the above example have i need this output after replace:" a = 'fjsrhmUhK60';

But what i am getting is: a =' ,fjsrhmUhK60';

everytime values replace but the associate comma didn't replace with empty or space.

my code: a = a.replace(b,'');

i don't want to remove all commas, reason after every unique value have its comma separator,

5 unique values have 4 commas:

654987987dsfdsf,5487987fsdfdsfsd,dsf8ds7987987,dsfdsfd779,sdfdsfdf

so only want to remove the matched value and the associated comma with space or empty.

Upvotes: 0

Views: 255

Answers (2)

CrayonViolent
CrayonViolent

Reputation: 32532

An alternative to the regex approach:

// arg1 : the source string
// arg2 : the values to remove from source string
function stringDiff(a,b){
  var b=b.split(',');
  return a.split(',').filter(function(v){
    return b.indexOf(v)==-1;
  }).join(',');
}

var a = 'gJDjOw0ern8,-4oCq2Vw4GQ,fjsrhmUhK60';
var b = 'gJDjOw0ern8,-4oCq2Vw4GQ';

stringDiff(a,b); // return:fjsrhmUhK60

Upvotes: 2

anubhava
anubhava

Reputation: 785058

You can use:

var r = a.replace(new RegExp(b + ",*"), '');
//=> "fjsrhmUhK60"

new RegExp(b + ",*") will build a regex using variable b followed by 0 or more comma.

PS: If a and b may contain regex meta characters then you will need to escape those chars in b. Something like this should work:

var r = a.replace(new RegExp(b.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + ",*"), '');

Upvotes: 1

Related Questions