I have a URL like:
http://url.test.com/account/name/pages/Stuff.html
I want to take 'Stuff' and apply that as a class to body.
<body class="Stuff">
...
</body>
How can I get the current URL?
How can I extract the text 'Stuff' after the final '/'
Then add the class 'Stuff' to body?
Not the shortest of code but substring is pretty fast so...
var page = window.location.href;
page = page.substring(page.lastIndexOf('/') + 1);
page = page.substring(0, page.lastIndexOf('.'));
document.body.className = page;
edited because I forgot to include part 3
1. url=location.href
2. fname=url.match(/.*\/(.*)\./)[1]
3. document.body.className=fname
See: stackoverflow.com:how-can-i-add-a-class-to-the-body-tag-using-jquery
I wanted to say that this question is a duplicate but I think your title expresses the problem better.
Related
I want to create a class for the title bars of pages that contain a certain piece of url.
My url is www.domainname.com/poste/XXX and I want to add the class only if the part after the .com contains only /poste/. I've seen examples for "contains this term" but it's not exactly what I'm looking for.
The existing class for the title bar is: .fusion-page-title-bar
Thanks in advance for the help and advice!
to check if a url contains any string, do the following:
if(window.location.href.indexOf(".com/poste") > -1) {
// do something
}
(checking if the index of a string is bigger than -1 is like asking if he is in there)
to conditonally add class:
element.classList.add("my-class");
combined it would be:
if(window.location.href.indexOf(".com/poste") > -1) {
titleClass = document.querySelector(".your-title-class");
titleClass.classList.add("conditionalClass");
}
*there are other solutions using jquery (like the one in #Wimanicesir comment), but it personaly prefer not using it :)
If I understand your problem is that you want to check if the URL ends with /poste/.
You can use the string function endsWith().
var url = window.location.href
console.log('Current url: ', url)
if (url.endsWith("js")) {
console.log('The url ends with js');
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
I've looked on similiar topics but no one seems to answer my question.
I've URL that looks like this:
https://dummy.com/job/test
I need to extract test so I am using:
function getIdentificator(){
let URL = window.location.pathname;
let Id = URL.slice(URL.lastIndexOf('/') + 1);
return Id;
}
It gives me what I want but sometimes the URL is different. For example:
https://dummy.com/job/testwz/something
I only need testwz.
Or:
https://dummy.com/job/test-ab?somethingmore2132
I only need test-ab.
Or:
https://dummy.com/job/test
I only need test.
Or:
https://dummy.com/job/5423
I need 5423 from this.
Value I'm interested in always appear after job/ but in different variations as said before. Key value may be followed by: nothing, / or ?.
Is there any way to extract this value in all examples with JavaScript? If not I can use jQuery as well.
Assuming your path will always begin with /job no matter the domain:
return window.location.pathname.split('/')[2]
I'm going to give you this example:
this is the question's url:
https://stackoverflow.com/questions/54556911/how-to-extract-specific-parameter-from-different-urls
if you do window.location.pathname you will get :
"/questions/54556911/how-to-extract-specific-parameter-from-different-urls"
now, if you do...
window.location.pathname.split('/').pop()
you will get:
how-to-extract-specific-parameter-from-different-urls
And I think this is the answer you are looking for.
For example I have a url like:
ftp://xxx:xxx#ftp.example.com/BigFile.zip
How can I get example.com from this url using javascript/jquery?
You can get the browser to parse the URL for you like this :
var a = document.createElement('a');
a.href = 'ftp://xxx:xxx#ftp.example.com/BigFile.zip';
var host = a.hostname;
That gets you the hostname, which in this case would be ftp.example.com, if for some reason you have to remove the subdomain, you can do
var domain = host.split('.');
domain.shift();
var domain = domain.join('.');
FIDDLE
Here's the different parts to a URL -> https://developer.mozilla.org/en-US/docs/Web/API/Location#wikiArticle
Here is using javascript RegExp
input = "ftp://xxx:xxx#ftp.example.com/BigFile.zip";
pattern = new RegExp(/ftp:\/\/\S+?#\S+?\.([^\/]+)/);
match = pattern.exec(input);
alert(match[1]);
You can also use i at the end of regex to make it case insensitive.
pattern = new RegExp(/ftp:\/\/\S+?#\S+?\.([^\/]+)/i);
You can use jquery like this:
var url = "ftp://xxx:xxx#ftp.example.com/BigFile.zip";
var ahref = $('<a>', { href:url } )[0]; // create an <a> element
var host = ahref.hostname.split('.').slice(1).join('.'); // example.com
You can have a regex to do this for you.
url = 'ftp://xxx:xxx#ftp.example.com/BigFile.zip'
base_address = url.match(/#.*\//)[0];
base_address = base_address.substring(1, base_address.length-1)
This would contain ftp.example.com though. You can fine tune it as per your need.
I just wanted to try/add something different (can't bet for performance or the general solution, but it works and hey ! without DOM/regexp involved):
var x="ftp://xxx:xxx#ftp.example.com/BigFile.zip"
console.log((x.split(".")[1]+ "." + x.split(".")[2]).split("/")[0]);
For the given case can be shortest since always will be ".com"
console.log(x.split(".")[1]+ ".com");
Another (messy) approach (and will work with .com.something:
console.log(x.substring((x.indexOf("#ftp"))+5,x.indexOf(x.split("/")[3])-1));
And well on this we're dependend about having "#ftp" and the slashes "/" (at least 3 of them or one after the .com.something) for example would not work with: ftp://xxx:xxx#ftp.example.com
Last update This will be my best
without DOM/RegExp, nicer (but also confusing) that the previous ones
solves the problem about having or don't the slashes,
still dependant on having "#ftp." in the string.
works with .com.something.whatever
(function (splittedString){
//this is a bit nicer, no regExp, no DOM, avoid abuse of "split"
//method over and over the same string
//check if we have a "/"
if(splittedString.indexOf("/")>=0){
//split one more time only to get what we want.
return (console.log(splittedString.split("/")[0]));
}
else{
return (console.log(splittedString));//else we have what we want
}
})(x.split("#ftp.")[1]);
As always it depends how maintainable you want your code to be, I just wanted to honor the affirmation about there's more than one way to code something. My answer for sure is not the best, but based on it you could improve your question.
If you are on http://www.cnn.com/2012/11/09/opinion/brown-pakistan-malala/index.html can you get Jquery to grab the index.html?
or if you are on http://www.washingtonpost.com/politics/decision2012/supreme-court-to-review-key-section-of-voting-rights-act/2012/11/09/dd249cd0-216d-11e2-8448-81b1ce7d6978_story.html have it return dd249cd0-216d-11e2-8448-81b1ce7d6978_story.html?
And for non extension defined pages such as this current one http://stackoverflow.com/questions/13317276/jquery-to-get-the-name-of-the-current-html-file can it return the last "file" in the "directory"structure, for example: jquery-to-get-the-name-of-the-current-html-file
Although not JQuery, you can access it using the following:
document.location.href.match(/[^\/]+$/)[0]
or
document.location.pathname.match(/[^\/]+$/)[0] in case of unneeded anchors/hash tags (#).
location.pathname.split('/').slice(-1)[0]
No need for jQuery. This will give you the last segment of the URL path (the bit after the last slash):
var href = document.location.href;
var lastPathSegment = href.substr(href.lastIndexOf('/') + 1);
function getCurentFileName(){
var pagePathName= window.location.pathname;
return pagePathName.substring(pagePathName.lastIndexOf("/") + 1);
}
I need to get the last 2 characters from the href of a link and place them into a string.
I'm sure this is fairly simple but I seem to be struggling.
Here's the link
test
I need to grab the "bb" part of the href.
Presuming link is a reference to the element:
var chars = link.href.substr(-2);
If you need to get the reference to the link, it is best to give the link an ID attribute, e.g. <a href="../mypage/?code=bb" id="myLink">, where myLink is something that describes the link's purpose. You can then do this:
var chars = document.getElementById('myLink').href.substr(-2);
Finally, if what you want is the code parameter from your link, it may be best to parse the URL into parts. If there is a chance that your URL may be more complex that what you've shown, you should do real URL parsing. As Rahul has pointed out in his answer there are some jQuery plugins that perform this function.
try
$(function() {
var res = $('a').attr('href').split(/=/)[1]
alert(res);
});
This will not grab the last two character, but everything after the = sign which works probably more generic. And even if the <center> cannot hold, regex could look like
$(function() {
var href = $('a').attr('href'),
res = /\\?code=(\w+)/.exec(href);
alert(res[1]);
});
var href = $('a').attr('href');
var last2char = href.substr(href.length-2);
You can try for some querystring plugins which might be a better option.