Reputation: 39
I have a JavaScript script I need help modifying...
I'd like to have URL parts extracted and set as classes of the html element.
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();
The hard part is the regex; this is how it should work:
Example URL:
http://www.somesite.com/Lists/Pages/ViewPage.aspx?ID=12
Should return (as classes of html element, of course):
lists pages viewpage aspx id 12
Feel free to edit the code around in anyway you seem fit...
Thanks in advance!
Upvotes: 0
Views: 4252
Reputation: 5060
You could make use of the URL API
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);
Upvotes: 0
Reputation: 11
var match = url.match(/^(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/);
var protocol = match[1],
domain = match[2],
path = match[3],
query = match[4],
fragment = match[5];
Upvotes: 1
Reputation: 17555
var matches = window.location.pathname.replace(/http:\/\/[^\/]+\//,'').match(/[\w\-\.!~\*\'"(),]+/g);
The regex complies with RFC 1738.
Converting each array element to lowercase should then be a trivial matter.
Upvotes: 2
Reputation: 8560
something like
var split = window.location.pathname.split(/\/|\?|&|=|\./g);
or if you want all in one string:
var classes = window.location.pathname.toLowerCase().replace(/\/|\?|&|=|\./g," ")
might do what you want
Upvotes: 3