0

I have a string like this "/blog/post1/"

how can i get the "post1" from this string in Jquery ?

I tried this but it returned empty.

var post_slug = $(this)[0].pathname.substring($(this)[0].pathname.lastIndexOf("/")).replace(/^\//, "");
1
  • split it! Commented Jun 28, 2012 at 15:25

4 Answers 4

1

If the format is always the same you can use:

var str = "/blog/post1/";
var piece = str.split('/')[2];​ // returns 'post1'
Sign up to request clarification or add additional context in comments.

Comments

1

Use a regular expresion, something like:

new RegExp("/blog/(\S+)/").exec("/blog/post1/");
["/blog/post1/", "post1"]

EDIT

It's RegExp, not Regex, my bad.

Comments

1

You can do it like this.

Live Demo

var str = "/blog/post1/";
arr = str.split('/');
var res = arr[arr.length-2];
alert(​res)​;

3 Comments

it's funny your answer looks almost identical to mine, posted 7 mins earlier ;)
We followed the same route :)
Yeah - just giving you a hard time :)
1

Use the JavaScript split function. Much simpler solution.

var url = "/blog/post1/";
var splitUrl = url.split("/");

// assuming known URL structure so always same index
var post_slug = splitUrl[splitUrl.length -2];

Working fiddle: http://jsfiddle.net/Rsrmk/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.