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.
4 Answers
Reset to default 3If 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
评论列表(0条)