javascript - Regex to get last word in URL betweenand- Stack Overflow

How do I get the last word in a URL that is URL betweenand?For example:Here I would want to get e

How do I get the last word in a URL that is URL between / and / ?

For example:

Here I would want to get extractMe from the URL.

How do I get the last word in a URL that is URL between / and / ?

For example:

http://mywebsite./extractMe/test

http://mywebsite./extractMe

http://mywebsite./settings/extractMe/test

http://mywebsite./settings/extractMe

Here I would want to get extractMe from the URL.

Share Improve this question edited Jun 21, 2012 at 9:54 user1469909 asked Jun 20, 2012 at 16:39 user1469909user1469909 311 silver badge3 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 3

If the URL is consistent, why not just use:

// Option 1
var url = "http://mywebsite./extractMe/test";
var extractedText = url.split("/")[3];

​// Option 2
// If when a trailing slash is present you want to return "test", use this code
var url = "http://mywebsite./extractMe/test/";
var urlAry = url.split("/");
var extractedText = urlAry[urlAry.length - 2];

​// Option 3
// If when a trailing slash is present you want to return "extractMe", use this:
var url = "http://mywebsite./extractMe/test/";
var urlAry = url.split("/");
var positionModifier = (url.charAt(url.length-1) == "/") ? 3 : 2;    
var extractedText = urlAry[urlAry.length - positionModifier];

Here's a working fiddle: http://jsfiddle/JamesHill/Arj9B/

it works with / or without it in the end :)

var url = "http://mywebsite./extractMe/test/";    
var m = url.match(/\/([^\/]+)[\/]?$/);

console.log(m[1]);

output: test

This accounts BOTH for URLS like http://mywebsite./extractMe/test and http://mywebsite./extractMe/

function processUrl(url)
{
    var tk = url.split('/');
    var n = tk.length;
    return tk[n-2];
}

Edited.

Regular Expression way:

var str = "http://example./extractMe/test";
var match = str.match(/\/([^\/]+)\/[^\/]+$/);

if (match) {
    console.log(match[1]);
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745404268a4626242.html

相关推荐

  • javascript - Regex to get last word in URL betweenand- Stack Overflow

    How do I get the last word in a URL that is URL betweenand?For example:Here I would want to get e

    12小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信