我需要从链接中获取一段文本并将其存储在变量中。我们说我有以下链接:
categories/name/products
你能不能帮助我获得名字'从链接考虑'类别'和'产品'言语永远不会改变。
提前致谢。
答案 0 :(得分:4)
您可以使用String.prototype.split()从网址字符串中获取基于零的数组:
var url = 'categories/name/products',
arr = url.split('/');
console.log(arr[1]);
答案 1 :(得分:1)
拆分字符串将是一个选项:
url.split("/")[1]
注意:正如connexo所提到的,如果你得到了网址
访问window.location.pathname
网址以/
开头,此解决方案中的索引必须为2
。
正则表达式将是另一种方式:
/categories\/(.+?)\/products/.exec(url)[1]
在这种情况下,索引具有不同的含义(第一个捕获组)并保持为1。
答案 2 :(得分: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];