Search code examples
javascriptregexxregexp

Remove String Between Substring from RegExp


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.


Solution

  • 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.