views:

52

answers:

4

Hi,

I need a regular expression that would split strings like itemXY where X and Y are integer (item23) to be used in javascript.

I would like it to return the integers x and y.

Thanks

+1  A: 

If all you need are last digits then:

\d+$

will do the work. \d+ means 1 or more digits, and $ means "at end". Then you can use result_string[0] and result_string[1] (of course you should check length):

var txt = "item25";
var result = txt.match(/\d+$/);
if (result != null)
    {
    var digits = result[0];
    alert(digits[0]);
    alert(digits[1]);
    }

You can also use regex groups like:

(\d)(\d)$
Michał Niklas
+1  A: 

are you trying to extrac "23" to a variable?

here you are:

/^item([0-9]+)$/

will extract any number from itemXXXXXX returning that number.

Tomasz Kowalczyk
yeah I will be extracting the number to a variable and then concatenate it to another string
Shouvik
+3  A: 

Assuming that you are always going to have two digits, use this:

var item = "item24";
var result = item.match(/(\d)(\d)$/);
var digit1 = result[1];
var digit2 = result[2];
Bennor McCarthy
Thanks this works perfectly.
Shouvik
+3  A: 

You don't need to bother the regex parser with this problem. If the first part of the string up to the number is always the same length, you can use slice() or substring():

var str = "item23";

alert(str.slice(4));
//-> 23

This would be faster and less complicated than a regular expression. If you need the numbers to be separated, you can just split them:

var arr = str.slice(4).split();
//-> ["2", "3"]
Andy E
Thanks I did not know about this method. Will try it out sometime... :)
Shouvik
@Shouvik: In my experience it's always better to avoid using regular expressions if there's a more suitable method available. I've updated my answer to include a solution that would give the same result as your accepted answer.
Andy E
Assuming the text is always 4 characters long.
Bennor McCarthy
@Bennor: or if the number at the end is always 2 digits long (which your answer also assumes), you could use `-2` instead of `4`.
Andy E
Agreed. I've actually upvoted this answer as I think it's better to use the right tool for the job.
Bennor McCarthy
@Bennor: thanks :-)
Andy E
@Andy thanks Andy. I will give it a try.
Shouvik