我有一个JavaScript脚本我需要帮助修改...
我想提取URL部分并将其设置为html元素的类。
var loc = window.location.pathname.match(REGEX_CODE_GOES_HERE);
// document.documentElement is the html element, this adds the class
if(loc) document.documentElement.className += " " + loc[1].toLowerCase();
困难的部分是正则表达式;这是它应该如何工作:
示例网址:
http://www.somesite.com/Lists/Pages/ViewPage.aspx?ID=12
应该返回(当然是html元素的类):
lists pages viewpage aspx id 12
随意编辑你认为合适的代码...
提前致谢!
答案 0 :(得分:3)
类似
var split = window.location.pathname.split(/\/|\?|&|=|\./g);
或者如果你想要一个字符串:
var classes = window.location.pathname.toLowerCase().replace(/\/|\?|&|=|\./g," ")
可能会做你想要的事情
答案 1 :(得分:2)
var matches = window.location.pathname.replace(/http:\/\/[^\/]+\//,'').match(/[\w\-\.!~\*\'"(),]+/g);
正则表达式符合RFC 1738。
将每个数组元素转换为小写应该是一件小事。
答案 2 :(得分:1)
var match = url.match(/^(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/);
var protocol = match[1],
domain = match[2],
path = match[3],
query = match[4],
fragment = match[5];
答案 3 :(得分:0)
您可以使用 URL API
<块引用>https://stackoverflow.com/a/65666418/1026105
var url = new URL("http://www.somesite.com/Lists/Pages/ViewPage.aspx?ID=12");
var pathnames = url.pathname.split('/');
// pathnames = ["", "Lists", "Pages", "ViewPage.aspx"]
// removes the first empty string
pathnames.shift();
// pathnames = [Lists", "Pages", "ViewPage.aspx"]
// lower case all entries in the array
pathnames = pathnames.map(i=>i.toLowerCase())
// pathnames = ["lists", "pages", "viewpage.aspx"]
// grab the last item since its the filename
var filename = pathnames.pop();
// filename = "viewpage.aspx"
// pathnames = ["lists", "pages"]
// create a css classes string that consists of the pathnames and the filename
var cssClasses = pathnames.concat(filename.split('.')).join(' ');
// now we need to grab the query params
var queryParams = new URLSearchParams(url.search);
for (const [key, value] of queryParams.entries()) {
cssClasses += ` ${key} ${value}`;
}
console.log('cssClasses =', cssClasses);