javascript - How to get a value by URL, preventing typos? -


i'd id (1337) out of every url can find below. what's best way? id numeric. maybe split "/" , take first numeric value? appreciate ideas.

actually url first one, i'd prevent typos.

here's jsfiddle: http://jsfiddle.net/vkjfw/

/* outputs "1337" */ var url = "http://www.mydomain.com/module/action/1337/";   /* error: outputs "action" */ // var url = "http://www.mydomain.com/module/action/1337";  /* error: outputs "action" */ // var url = "http://www.mydomain.com/module/action/1337#";   /* error: outputs "" */ // var url = "http://www.mydomain.com/module/action/1337//";  /* error: outputs "bla" */ // var url = "http://www.mydomain.com/module/action/1337/bla/?x=y";  var url_parts = url.split("/"); var id        = url_parts[url_parts.length-2];  alert(id); // should output "1337" everytime! 

var id        = parseint(url_parts[5]); 

works of examples.

you use regular expression find first number:

var reg = /\d+/; var id = reg.exec(url); 

using regular expression might more robust solution.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -