admin管理员组文章数量:1426072
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]);
}
本文标签: javascriptRegex to get last word in URL betweenand Stack Overflow
版权声明:本文标题:javascript - Regex to get last word in URL betweenand- Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745404267a2657178.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论