Daniel G. Reina Daniel G. Reina - 1 year ago 73
Javascript Question

Match all character before numbers

I want to do operations with the numbers in a string, but the operation depends on the char before that number, so I need to get the char before any number in a string. Note that the char before a number could be another number.

So far I've done

, but this is not matching the case where there's a number before another number. For example:

positions: 0123456789012
string: a a4 bb4 c44c


  1. a4

  2. b4

  3. c4

It doesn't match

How can I match this one too?

Answer Source

You may use a much simpler regex:


See the regex demo

This regex matches any char except newline and carriage return (.) that is a any char other than LF/CR followed with a digit.

This pattern does not match an empty string and does not require additional code to check if we matched an empty string (like if (m.index === re.lastIndex) re.lastIndex++; in anubhava's answer, that is redundant even in that solution, and this way you can avoid concatenating captured group values).

The actual value is stored in Capture group 1 that is inside a positive lookahead to allow getting overlapped matches. Since the captures are lost if we use str.match(re), we have to rely on RegExp#exec inside a loop.

var re = /(?=(.[0-9]))./g; 
var str = 'a a4 bb4 c44c';
var res = [];
while((m=re.exec(str)) !== null) {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download