You can't literally do that with a single match
call. Once the character is consumed, it's consumed. However, Wiktor points to a duplicate (I should have realized) with an answer that does a very clever thing with repeated exec
calls instead.
Another option, depending on the real-life situation, would be to get close enough that you can fix it with post-processing, using a positive lookahead assertion. We can say "only match a
if it's immediately followed by b
— but don't consume b
". Then, if we have a
results, we know they're really ab
results (wouldn't have matched otherwise) and we can change them accordingly:
var result = "abc".match(/a(?=b)|bc/g);
if (result) {
result = result.map(function(entry) {
return entry === "a" ? "ab" : entry;
});
}
Or with ES2015+:
let result = "abc".match(/a(?=b)|bc/g);
if (result) {
result = result.map(e => e === "a" ? "ab" : e);
}
If the a
part varies, you may be able to use other checks (such as entry.length === 1
, or !entry.endsWith("b")
, etc.) depending on the real data.
Live example (ES5 and earlier version assuming a
):
var result = "abc".match(/a(?=b)|bc/g);
if (result) {
result = result.map(function(entry) {
return entry === "a" ? "ab" : entry;
});
}
console.log(result);