1

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.

1
  • thanks for fixing the formatting nickf, I didn't know how to type an anchor tag without having jeff's code strike it out. Commented Oct 24, 2008 at 3:02

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Nevermind, I solved it with a simple

'<a href="pic/5" id="piclink"><img src="thumb/5" /></a>'.match(/[0-9]/);

1 Comment

This will only match one digit, if you want to match a two digits number you should use [0-9]+ or \d+
1

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();

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

1 Comment

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.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.