2016-12-21 50 views
-1

我需要从链接中获取一段文本并将其存储在变量中。比方说,我有以下链接:使用JavaScript从当前网址获取一段文本

categories/name/products 

能否请你帮我从考虑到“类别”和“产品”的话永远不变的链接获取“名称”。

在此先感谢。

+1

https://开头的CSS技巧。 com/snippets/javascript/get-url-and-url-parts-in-javascript/ – connexo

+0

现在是什么?当前的URL或链接? – connexo

+0

对不起@connexo,我没有注意到这个评论。下次将更加关注:) –

回答

4

您可以使用String.prototype.split()获得零基于阵列出你的URL字符串:

var url = 'categories/name/products', 
 
    arr = url.split('/'); 
 

 
console.log(arr[1]);

+0

这将返回实际url中的第一个单词。 (例如:www.google.com/search/something/else它会返回搜索而不是东西) –

+1

您从'String.prototype.split()'中获得的数组是基于零的 –

+0

尝试'console.log(window .location.pathname.split('/')[1])'在这个页面的开发者控制台里面,你会看到它会选择问题而不是41259089 –

1

分割字符串是一个选项:

url.split("/")[1] 

注意:如connexo提及,如果你得到的网址为

通过访问window.location.pathname

链接开始与一个/和索引必须是在该溶液中2

正则表达式将是另一种方式:

/categories\/(.+?)\/products/.exec(url)[1] 

在这种情况下,指数有不同的含义(第一捕获组),并保持1

+1

0在这里应该是1 –

+0

1在这里应该是2,因为通过访问window.location.pathname来完成URL并且该字符串总是以'/'开头。 – connexo

+0

没错。更正它并提供正则表达式解决方案。 –

1
// get the current url part after top level domain 
var currentUrl = window.location.pathname; // will be "/categories/name/products" 
// split the string at the/
// will give you [ "", "categories", "name", "products" ] 
// Then access array element with index 2 (index on arrays is 0-based) 
var extract = currentUrl.split("/")[2];