Need help! I've been looking for a solution for this seemingly simple task but can't find an exact one. Anyway, I'm trying to add custom #id to the tag based on the page's URL. The script I'm using works ok when the URLs are like these below.
- http://localhost.com/index.html
- http://localhost.com/page1.html
- http://localhost.com/page2.html
-> on this level, <body> gets ids like #index, #page1, #page2, etc...
My question is, how can I make the body #id still as #page1 or #page2 even when viewing subpages like this?
- http://localhost.com/page1/subpage1
- http://localhost.com/page2/subpage2
Here's the JS code I'm using (found online)
$(document).ready(function() {
var pathname = window.location.pathname;
var getLast = pathname.match(/.*\/(.*)$/)[1];
var truePath = getLast.replace(".html","");
if(truePath === "") {
$("body").attr("id","index");
}
else {
$("body").attr("id",truePath);
}
});
Thanks in advance!
edit: Thanks for all the replies! Basically I just want to put custom background images on every pages based on their body#id. >> js noob here.
http://localhost.com/page2/subpage2 - > my only problem is how to make the id as #page2 and not #subpage2 on this link.
Using the javascript split function might be of help here. For example (untested, but the general idea):
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
$('body').id = segments[0];
Also, you might want to consider using classes instead of ID's. This way you could assign every segment as a class...
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
for (var i = 0; i < segments.length; i++) {
$('body').addClass(segments[i]);
}
EDIT:
Glad it worked. Couple of notes if you're planning on using this for-real: If you ever have an extension besides .html that will get picked up in the class name. You can account for this by changing that replace to a regex...
var url = window.location.href.replace(/http[s]?:\/\//, '');
// Trim extension
url = url.replace(/\.(htm[l]?|asp[x]?|php|jsp)$/,'');
If there will ever be querystrings on the URL you'll want to filter those out too (this is the one regex I'm not 100% on)...
url = url.replace(/\?.+$/,'');
Also, it's a bit inefficient to have the $('body') in every for loop "around" as this causes jQuery to have to re-find the body tag. A more performant way to do this, especially if the sub folders end up 2 or 3 deep would be to find it once, then "cache" it to a variable like so..
var $body = $('body');
for ( ... ) {
$body.addClass( ...
}
Your regex is only going to select the last part of the url.
var getLast = pathname.match(/./(.)$/)[1];
You're matching anything (.*), followed by a slash, followed by anything (this time, capturing this value) and then pulling out the first match, which is the only match.
If you really want to do this (and I have my doubts, this seems like a bad idea) then you could just use window.location.pathname, since that already has the fullpath in there.
edit: You really shouldn't need to do this because the URL for the page is already a unique identifier. I can't really think of any situation where you'd need to have a unique id attribute for the body element on a page. Anytime where you're dealing with that content (either from client side javascript, or from a scraper) you should already have a unique identifier - the URL.
What are you actually trying to do?
Try the following. Basically, it sets the id to whatever folder or filename appears after the domain, but won't include a file extension.
$(document).ready(function() {
$("body").attr("id",window.location.pathname.split("/")[1].split(".")[0]);
}
You want to get the first part of the path instead of the last:
var getFirst = pathname.match(/^\/([^\/]*)/)[1];
If your pages all have a common name as in your example ("page"), you could modify your script including changing your match pattern to include that part:
var getLast = pathname.match(/\/(page\d+)\//)[1];
The above would match "page" followed by a number of digits (omitting the 'html' ending too).
Related
This is my first experience with JS, so please forgive the noob question.
I'm trying to make a userscript for a phpBB forum that'll allow me to automatically bookmark every topic I create.
My approach is to add an onclick listener to the submit button.
I'll use the code found in another question:
var submit = document.getElementsByTagName('input')[0];
submit.onclick = function() {
;
}
Before that though I want to find a link to bookmarking the topic in one of the hrefs on the page and store it as a variable.
I know that it will always take the form of
<a href="./viewtopic.php?f=FORUM_NUMBER&t=TOPIC_NUMBER&bookmark=1&hash=HASH"
The final code should look something like (hopefully it's the correct form)
var link = THE LINK EXTRACTED FROM THE MATCHED HREF
var submit = document.getElementsByTagName('input')[0];
submit.onclick = function() {
setTimeout(function(){ window.location.href = 'link'; }, 1000);
}
My issue is I don't know how to approach locating the href that I need and getting the link from it. Haven't found any similar questions about this.
Thanks in advance for any help
Maybe something like this?
var anchors = document.getElementsByTagName('a'); // get all <a> tags
var link = '';
if (anchors) {
// getAttribute(attributeName) gets the value of attributeName (in your case, the value of 'href' attribute
// .map(), .find() and .filter() are available methods for arrays in JS
// .startsWith() is an available method for matching strings in JS.
// You can even experiment with other regex-based string matching methods like .match()
// Use one of the following lines, based on what you require:
// to get the first matching href value
link = anchors.map(anchor => anchor.getAttribute('href')).find(url => url.startsWith('./viewtopic.php')); // or provide a better regex pattern using .match()
// to get all matching href values as an array
link = anchors.map(anchor => anchor.getAttribute('href')).filter(url => url.startsWith('./viewtopic.php')); // or provide a better regex pattern using .match()
}
Since you're not new to coding, check out this documentation if you're new to JS :)
Happy coding!
You can try document.getElementsByTagName("a"); which returns a collection of all the <a></a> loaded in the dom.
Then you can find it in the list and and use .href to get it's href attribute.
I have an Array with one or more entries. Each one is a string (List of urls in open Tabs via Firefox SDK). I want to check if a specific url is already opened in some of the tabs (nothing special till now).
My problem is, that the url in tab list can have four diffrent fourms. For example:
Url I want to find in the tablist:
https://cmsr-author.de/cf#/content/test/de.html
But the url can also look like this:
https://cmsr-author.de/content/test/de.html
https://cmsr-author.de/test/de.html
https://cmsr-author.de/cf#/test/de.html
Of course the last part of the url (after /test/...) is always something diffrent. If I wasn't able to find one of the four urls in the tablist i want to call some other action.
My Solution till now is to build some if-chain:
if (res !== url1) {
if (res !== url2) {
if ...
But i thought there must be some more elegant way. Maybe via RegEx? I already have a capture to catch the first part (which stays the same https://cmsr-author.ws...) with it four forms. But i dont know how to implent this probably.
var urls = ["https://cmsr-author.de/content/test/de.html","https://cmsr-author.de/test/de.html","https://cmsr-author.de/cf#/test/de.html"]
var filtered = urls.filter(function(url)
{
return url.indexOf("cf#") > -1 && url.endsWith("/test/de.html")
})
var contains = filtered.length > 0
console.log(contains)
If you want to use regex you can do this by using groups for the middle part, which is explained in detail here: http://www.regular-expressions.info/refcapture.html
Practically, your regex would look something like that:
https:\/\/cmsr-author\.de\/(content|...|...)\/de\.html
Where ... must be replaced by the middle parts of the url which differ.
Note that | is "or" used to provide multiple possibilities within the group. The character / and . must be escaped since they have special roles in regex.
I hope that helps!
My English is not good,Do not fully understand what you mean,According to my idea,You should need a regular expression,Only to match the first.If I am wrong,
please # me.
I hope that helps!
var reg = /^https:\/\/cmsr\-author\.de\/cf#\/(?:\w+\/)+test\/de\.html$/gi;
var str1 = "https://cmsr-author.de/cf#/content/test/de.html";
var str2 = "https://cmsr-author.de/content/test/de.html";
var str3 = "https://cmsr-author.de/test/de.html";
var str4 = "https://cmsr-author.de/cf#/test/de.html";
console.log(reg.test(str1));
console.log(reg.test(str2));
console.log(reg.test(str3));
console.log(reg.test(str4));
I have 2 index pages with approx. 150 links on each. I would rather maintain 1 page and just generate the links dynamically based on a variable value. For example create a list of links. link1, link2, link3... and based on a variable value being 'true' replace those links with list of alternate links i.e. altlink1, altlink2, altlink3...
I have figured out how to do this once but rather than writing the same code over and over for each link I was wondering if there was a faster way. Like creating a list "a" and corresponding list "b" or something like that. I have included my current code below and I look forward to your advice.
<script type="text/javascript">
// link rewriter
var hostadd = location.host;
var vendor = '999.99.999.99';
var localaccess = 'somesite.com';
$(document).ready (
function link_switcher(){
//if not a vendor route to alternate website
if (hostadd != vendor) { $("a[href= 'https://www.somelink1.com']").attr ('href', 'https://www.alternatelink1.com') }
});
</script>
is it possible to create an array and then javascript that would say replace link1 in array a with alternatelink1 in array b?
It's still not entirely clear what you're trying to do, but if you want to rewrite all links based on a lookup table that tells you what link to convert to what, here's how you could do that:
// Table of links.
// Key is original page source URL
// Data is link to change it to
var linkData = {
"http://www.google.com": "http://www.bing.com/",
"http://mail.google.com/mail/?shva=1#inbox": "http://www.hotmail.com"
};
// find every link in the page and change it if it's value is found in the linkData table
$("a").each(function() {
var link = this.getAttribute("href"); // use getAttribute to get what was actually in the page, perhaps not fully qualified
if (linkData[link]) {
this.href = linkData[link];
}
});
If the link is not found in the table, it will not be modified. If there was some pattern to the modification, it might be possible to code that pattern and not have to list every link in the table, but you haven't shared any info about a pattern.
And, a working jsFiddle example: http://jsfiddle.net/jfriend00/Cvj8C/.
I hava a url like
mysite.net/home/index/page/XX
while XX is any number. I need to replace XX and remove everything that might be behind XX. So I would like to remove everything behind page/ by replacing it with a number.
There are a lot of methods for string manipulation http://www.w3schools.com/jsref/jsref_obj_string.asp
I know how to perform this but I am not sure which methods to use. So I ended with getting the lastIndexOf("page/"). So this +1 would give me the starting point for replacing the string. The entire length of the string would be the ending point.
Any ideas?
The following code will do the trick, by using regular expression:
"mysite.net/home/index/page/XX".replace(/\/page\/.*/, '/page/123')
var url = "mysite.net/home/index/page/XX"
return url.substr(-(url.length - (url.lastIndexOf("page/") + 5))))
I don't get your problem because you may have found everything you need...
var yourURI = "mysite.net/home/index/page/XX";
var theDelimiter = "page/";
var yourNewIndex = "42";
var yourNewURI = null;
var lastIndexOfDelimiter = yourURI.lastIndexOf(theDelimiter);
if (lastIndexOfDelimiter != -1)
{
yourNewURI = yourURI.substr(0, lastIndexOfDelimiter + theDelimiter.length) + yourNewIndex;
}
Is that what you want?
This isn't a direct answer to your question, but the way I solve this kind of problem is to have the server calculate a 'base url' (mysite.net/home/index/page/ in your case), and write it to a js variable at the time the page is built.
For two different ASP.NET MVC versions (there would be something similar you could do in any other framework) this looks like this:
var baseUrl = '#ViewBag.BaseUrl';
or
var baseUrl = '<%: ViewData["BaseUrl"] %>';
This has the big advantage that the page JS doesn't start to know about URL formation, so if you change your URL routing you don't find little breakages all over the place.
At least for ASP.NET MVC, you can use the frameworks routing API to generate the base URL at the server side.
How would I go about trimming/stripping the URL down to the page name...
So: http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html
Would become: apage.html
Any ideas?
you do not need jquery:
var url = window.location.href;
var page = url.substring(url.lastIndexOf('/') + 1);
Edit: a good point of the possible query string:
// it might be from browser & / anywhere else
var url = window.location.href;
url = url.split('#').pop().split('?').pop();
var page = url.substring(url.lastIndexOf('/') + 1);
ok, if the location object is available, use pathname gives better result as show below, however, a url can be a string or something directly from text field or span/label. So above solution should have its place.
With location and any link (<a>) elements on the page, you get a load of properties that give you specific parts of the URL: protocol, host, port, pathname, search and hash.
You should always use these properties to extract parts of the URL in preference to hacking about with href and probably getting it wrong for corner cases. For example, every solution posted here so far will fail if a ?query or #fragment is present. The answers from Rob and digitalFresh attempt to cope with them, but will still fail if a / character is present in the query string or fragment (which is valid).
Instead, simply:
var pagename= location.pathname.split('/').pop();
Most of the solutions here are not taking advantage of the window.location object. The location object has this wonderful thing called pathname which returns just the path, no query string, host, protocol, hash, etc.
var mypage = window.location.pathname.split("/").pop();
You could do something like this:
document.location.href.split('/').pop();
Edit: you probably want to get rid of the query string if there is one also:
document.location.href.split('/').pop().split('?').shift();
Edit 2: this will also ignore an anchor in the url if there is one
document.location.href.split('/').pop().split(/\?|#/).shift();
This should also exclude query and hash values.
var path = location.href;
path = path.substring(path.lastIndexOf("/") + 1);
path = path.split("?")[0].split("#")[0];
console.debug(path);
Haven't tested so compeltely guessed, but I'm sure something like this will do :-)
var url = 'http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html';
var page = url.split('/');
alert(page[page.length-1]);
EDIT Tested under jsfiddle and it was wrong, the above code should now work :-)