Link to home
Start Free TrialLog in
Avatar of renisenbb
renisenbb

asked on

Javascript: Need help with a regex

I have an id that i want to match such that the last "_<digit(s)>" is ignored.
For eg, if i have an id="someid_2_0_3", the match should return "someid_2_0".
If the id="anotherid_31_2", the match should return "anotherid_31".
ASKER CERTIFIED SOLUTION
Avatar of zzynx
zzynx
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of renisenbb
renisenbb

ASKER

var cellregex = new RegExp(/(.*)_\d$/);
var c = "someid_2_0_3";
var s = c.match(cellregex);
alert (s);

This returns: someid_2_0_3,someid_2_0

How do i get it to only return the second value (someid_2_0)
I see, it is returning an array. Thanks.
You don't need a regex for this. Sting operations would do well.
str.substring(1, str.lastIndexOf('_') - 1)

Open in new window

Characters from 1st position to one_position before the last occurrence of '_' - 1.
alert(s[1]);

Open in new window

Thanx 4 axxepting