views:

1207

answers:

3

I need to match something in the form

<a href="pic/5" id="piclink"><img src="thumb/5" /></a>

to find the number, in this case 5, using javascript. I have no idea how to use regexes so I was wondering if anyone here could help out. Thanks!

+1  A: 

Nevermind, I solved it with a simple

'<a href="pic/5" id="piclink"><img src="thumb/5" /></a>'.match(/[0-9]/);
num1
This will only match one digit, if you want to match a two digits number you should use [0-9]+ or \d+
CMS
You're right, thanks. This explains one of the bugs I had :)
num1
+2  A: 

Just to make sure you know what's going on, the pattern you posted in your own answer will match exactly one digit between 0 and 9.

If you want to match integers with one or more digits, you might try the pattern

/[0-9]+/

Check out Wikipedia's article on Regular Expressions for a great overview. Regular Expressions can seem overwhelming if you're just starting out, but once you get a handle on the basic syntax, they're incredibly useful and powerful.

Rudi
+1  A: 

It's not clear what the general case is (the specific in your example is "5"). If you're trying to extract the last segment of the URI path, you can achieve it without employing a regex:

Using jQuery (not necessary, but a really effective tool if the context permits):

$('#picklink > img').attr('src').split('/').pop();

"$('#picklink > img').attr('src')" is jQuery and the ".split('/').pop();" part is straight javascript.

micahwittman
I really like this solution, as it works if I change my mind on how the link should be later on (I might use a number somewhere else in the link on accident and wonder why my code was wrong.)
num1