0

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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

You understand what i want, without any bug its working perfectly, amazing job Crayon.
1

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, '\\$&') + ",*"), '');

9 Comments

Your first example work well it create new bug, which is i have 4 unique id's now: 'saHJ_S-MEiY,SEUXMVt6Fik,6KtOcX8xOY8,jmMn4zzdyqc,ARTDCAGGS5k And i matched: var b = 'saHJ_S-MEiY,ARTDCAGGS5k'; you code not work when i match the first id and the last id, but between ids i can match and replace with associate comma now, can you check this what's now new issue its.
Didn't get your comment. Can you clarify what is a and what is b and what is expected output?
bad regex. try with a='foo,bar';b='bar'; or a='foo,bar';b='foobar,bar'
@CrayonViolent: Use: a.replace(new RegExp(",*" + "\\b" + b + ",*"), '')
still bad regex. again, try a='foo,bar';b='foobar,bar'
|

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.