jabs83
jabs83

Reputation: 190

How do i match text after a specific character?

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

Answers (4)

Braj
Braj

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

enter image description here

Upvotes: 1

CaffGeek
CaffGeek

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

adeneo
adeneo

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

FIDDLE

or you can just split and pop it

var result = url.split('#/').pop();

Upvotes: -1

anubhava
anubhava

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

Related Questions