user3496974
user3496974

Reputation: 145

Find last string after delimiter: Javascript

I have a url with many delimiters '/'.

I want to find the string after the last delimiter. How can I write a javascript code?

for eg if my url is

localhost/sample/message/invitation/create/email

I want to display 'email' as my output.

Upvotes: 0

Views: 132

Answers (4)

Anoop
Anoop

Reputation: 23208

Usng simple regex

var str = "localhost/sample/message/invitation/create/email";
var last = str.match(/[^/]*$/)[0]";

Above regex return all character after last "/"

Upvotes: 0

D Mishra
D Mishra

Reputation: 1578

var url="localhost/sample/message/invitation/create/email";
  url.split("/").pop()

or

var last=$(url.split("/")).last();

Upvotes: 0

Alaeddine
Alaeddine

Reputation: 1677

Splitting on a regex that matches spaces or hyphens and taking the last element

var lw = function(v) {
  return (""+v).replace(/[\s-]+$/,'').split(/[\s-]/).pop();
};
lw('This is a test.'); // returns 'test.'
lw('localhost/sample/message/invitation/create/email,'); // returns 'email,'

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

var last = input.split("/").pop();

Simples!

Upvotes: 2

Related Questions