Henry
Henry

Reputation: 1424

extract data by regex in javascript

I have this string:

"irrelevant(AB:1;CD:2;EF:3)"

and I need to find a way to extract the AB, CD and EF values (1, 2 and 3 in the example) either as individual variables or as an array, using only JS functions.

The irrelevant part may have ( ) : and ; but the (AB:1;CD:2;EF:3) part is always at the end. The values are always numeric, of variable length, and the labels are always 2 uppercase letters.

Thanks for any assistance.

Upvotes: 4

Views: 8680

Answers (1)

atiruz
atiruz

Reputation: 2858

Try this code:

var txt = "irrelevant(AB:1;CD:2;EF:3)";
var m = txt.match(/(?:([A-Z]{1,}))\:([0-9]{1,})/gi);
var str = "";
for (var i = 0; i < m.length; i++) {
    var p = m[i].split (":");
    str += "Letters: " + p[0] + " - Number: " + p[1] + "\n";
}
​alert (str)​;

Look at this example in action Demo

Regards, Victor

Upvotes: 3

Related Questions