4

I write this code for remove string from 'a' to 'c'

var str = "abcbbabbabcd";
var re = new RegExp("a.*?c","gi");
str = str.replace(re,"");
console.log(str);

The result in console is "bbd"

But the result that right for me is "bbabbd"

Can I use Regular Expression for this Problem ?

Thank for help.

  • This does correct remove strings from 'a' to 'c'. Perhaps you rather mean strings that go from 'a' to 'c' but excluding 'a'? If that is so please edit the question so it's clear. – Spencer Wieczorek Oct 08 '15 at 06:03

4 Answers4

2
a(?:(?!a).)*c

Use a lookahead based regex.See demo..*? will consume a as well after first a.To stop it use a lookahead.

https://regex101.com/r/cJ6zQ3/34

EDIT:

a[^a]*c

You can actually use negated character class as you have only 1 character.

vks
  • 67,027
  • 10
  • 91
  • 124
1

The g means it's a global regexp, meaning it picks up both the abc and abbabc in the string. So this does properly remove the items from a..c. It seems you saw only two abc and missed the abbabc. The result bbd is actually correct as it does indeed "remove string from 'a' to 'c'".

abcbbabbabcd => bbd

Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
0

You need to update your regex to a[^ac]*?c , this will avoid character a and c between a and c

var str = "abcbbabbabcd";
var re = new RegExp("a[^ac]*?c","gi");
str = str.replace(re,"");
console.log(str);

Regular expression visualization

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

Here is one more way.

var str = "abcbbabbabcd";
var str= str.replace(/abc/g, ""); 
console.log(str);
A DEv
  • 255
  • 1
  • 19