What's the best way to grab the number in this url string with jQuery or vanilla javascript?
"/o开发者_JS百科rganizations/1/media/videos/11"
I would like to just grab that 1
. Not sure how to exactly do that.
Any ideas?
just split the location.pathname and grab that index. this is vanilla javascript
var num = window.location.pathname.split("/")[2]
var myString = "/organizations/1/media/videos/11";
var myArr = myString.split('/');
alert(myArr[2]);
That should be sufficient, but it definitely depends on what the pattern of your URLs will be.
Demo: http://jsfiddle.net/XYEAh/
Regular Expression Solution:
var str = "/organizations/1/media/videos/11";
var re = /\/(\d+)\//;
var num = null;
var data = str.match(re);
if(data){
num = parseInt( data[1], 10 );
}
alert(num);
精彩评论