javascript quicky

Soldato
Joined
6 Feb 2004
Posts
20,852
Location
England
i have some urls and i simply want to extract the number in bold.

htttp://userserve-ak.last.fm/serve/_/176111/The+Verve.jpg

how can i do that? :o

EDIT: i've very crudely managed to come up with this....

Code:
end = urls[i].lastIndexOf("/");
start = urls[i].lastIndexOf("/",end-1) + 1;
num = urls[i].substring(start,end);

if anybody has anything tidier?? :)
 
Last edited:
Code:
package regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ocukReg {

	public static void main(String args[]){
		String testString = "htttp://userserve-ak.last.fm/serve/_/176111/The+Verve.jpg";

		Pattern myPattern = Pattern.compile("\\_\\/([0-9]+)");
		Matcher myMatcher = myPattern.matcher(testString);
		String Extracted ="";
		while(myMatcher.find()){
			Extracted = myMatcher.group(1);
		}
		System.out.println(Extracted);
	}
}

Ops thought this was Java rather than Javascript, not sure if it'll work in that case as I know nothing about Java script!
 
Code:
package regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ocukReg {

	public static void main(String args[]){
		String testString = "htttp://userserve-ak.last.fm/serve/_/176111/The+Verve.jpg";

		Pattern myPattern = Pattern.compile("\\_\\/([0-9]+)");
		Matcher myMatcher = myPattern.matcher(testString);
		String Extracted ="";
		while(myMatcher.find()){
			Extracted = myMatcher.group(1);
		}
		System.out.println(Extracted);
	}
}

Ops thought this was Java rather than Javascript, not sure if it'll work in that case as I know nothing about Java script!

There's regex objects available in JS (like just about every other language)

To the OP, you might not use them for this; but I highly recommend learning them for the future - they are really powerful. :)
 
Try this:

Code:
var url = "http://userserve-ak.last.fm/serve/_/176111/The+Verve.jpg";
var matches = url.match(/^.+\/(\d+)\/.+?$/);
var number = matches[1];

This problem essentially amounts to extracting information from a string based on some simple syntactic rules, which is precisely what regular expressions are designed for. It really, really is worth learning them :) There's an online tool you can use to help you here:

http://www.gskinner.com/RegExr/

The expression I gave basically says "take the group of digits that occurs between the final and penultimate slashes, allowing any character to occur outside these slashes".
 
Last edited:
thanks for the tips. i've always known they're supremely powerful. it just makes my eyes glaze over looking at them. :D

one day.....:o
 
Back
Top Bottom