Reputation: 190
I have a url that looks like this:
http://mysite/#/12345
How do I retrieve the text using regex after the /#/ which is essentially a token that I would like to use elsewhere in my javascript application?
Thanks.
Upvotes: 0
Views: 63
Reputation: 46841
Try with JavaScript String methods.
var str='http://mysite/#/12345';
alert(str.substring(str.lastIndexOf("/#/")+3));
You can try with String'smatch()
method as well that uses regex expression.
Just get the matched group from index 1 that is captured by enclosing inside the parenthesis (...)
var str='http://mysite/#/12345';
alert(str.match(/\/#\/(.*)$/)[1]);
Upvotes: 1
Reputation: 22054
Let the browser do it for you
var parser = document.createElement('a');
parser.href = "http://mysite/#/12345";
alert(parser.hash.substring(2)); //This is just to remove the #/ at the start of the string
JSFiddle: http://jsfiddle.net/gibble/uvhqa4yv/
Upvotes: 1
Reputation: 318182
Using the browser to parse the URL and getting the hash would probably be most reliable and would work with any valid URL
var url = 'http://mysite/#/12345';
var ele = document.createElement('a');
ele.href = url;
var result = ele.hash.slice(2);
or you can just split and pop it
var result = url.split('#/').pop();
Upvotes: -1
Reputation: 784958
You don't need regex here, just String#substr
using String#indexOf
:
var s = 'http://mysite/#/12345';
var p ='/#/'; // search needle
var r= s.substr(s.indexOf(p) + p.length);
//=> 12345
Upvotes: 4