Tylerr
Tylerr

Reputation: 39

Regex for extracting URL parts?

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

Answers (4)

Craig Wayne
Craig Wayne

Reputation: 5060

You could make use of the URL API

https://developer.mozilla.org/en-US/docs/Web/API/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

Filip
Filip

Reputation: 11

var match = url.match(/^(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/);
var protocol = match[1],
    domain   = match[2],
    path     = match[3],
    query    = match[4],
    fragment = match[5];

Upvotes: 1

bcosca
bcosca

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

morja
morja

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

Related Questions