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
Related
What I'm about to ask may sound stupid but I've been trying to figure it out for a few days now. I want to generate a link to a site:
example.github.io/Example/Example
That has a variable or something at the end of it
example.github.io/Example/ExampleVariable
and then read that variable as the page loads. In a perfect world it would look something like this:
http://Example.github.io/Example/Example<script>function(){}</script>
I also need to make sure that the page the user actually goes to or at least ends up on is the original link: i.e.
example.github.io/Example/Example
Any help would be greatly appreciated.
Also if anyone is wondering. Yes it is on github if that applies. I barely know PHP so that's not the best. It's for a ToDo list manager app I've made. There is a load function so users can share lists. The Load string (variable I'm trying to read) looks like this: /LoadNAME#THEME#Item A,Item B,ect.
If you're using github pages you could use URL parameters. In that case the url would look something like this: http://mypage.github.io/test/?myparam=value
Then you could query that with javascript and execute something based on that url parameters the url contains.
Alternatively, you can use this hash # old trick then after it use slashes
example.github.io/Example/#/var1/var2/var3
then using the window.location.href with couple split() uses will provide you
with an array of parameters.
/* URL in address bar:
http://localhost/test/js-url-parameters/#/str1/str2/str3/
*/
var docURL = window.location.href,
params = [];
// filter out the website origin "example.github.io" in the OP example
docURL = docURL.replace(window.location.origin, '');
// if /#/ found then we have URL parameters
// grabbing the parameters part of the URL
if (docURL.indexOf('/#/') > -1) {
docURL = docURL.split('/#/')[1];
if (docURL != '') {
// omit the last forward slash if exist
if (docURL[docURL.length - 1] == '/') {
docURL = docURL.substring(0, docURL.length - 1);
}
// split the URL final string o get an object with all params
params = docURL.split('/');
console.log(params);
}
} else {
console.log('No URL parameters found');
}
/* Output:
["str1", "str2", "str3"]
*/
UPDATE:
The above outputs all variables as string, so to retrieve numeric values you need to parseInt -or parseFloat() depending on your case.
For example, if for this URL:
http://localhost/test/js-url-parameters/#/str1/22/str3/
The above code will output ["str1", "22", "str3"], while we suppose to have 22 as integer, to fix this just add this:
// for each elements in params, if it is Not a Number (NaN) we return
// it as it is, else it's a nubmer so we parseInt it then return it
for(var i in params){
params[i] = isNaN(parseInt(params[i])) ? params[i] : parseInt(params[i]);
}
the above snippets go rights after the params = docURL.split('/'); line.
Now the URL:
http://localhost/test/js-url-parameters/#/str1/22/str3/ outputs ["str1", 22, "str3"], as you see now 22 is a number rather than a string.
What I'm trying to do is fetch a single piece of a string without using the hashtag element in the url. I already have a functioning code but it needs altering. So, how do I fetch any part of the url after ?.
Say I have ?fx=shipment+toys/fish-fix-fx/ as my url string; I want the button to show if shipment or fish or fx was my choice of selections for example.
Buttons showing with hastag: http://jsfiddle.net/66kCf/2/show/#iphone
Original JSFiddle (buttons not showing): http://jsfiddle.net/66kCf/2/
I want the iPhone buttons to show if fix was my choice: http://jsfiddle.net/66kCf/2/show/?fx=shipment+toys/fish-fix-fx/
try doing it with .split() and.match() like this...
var keys = window.location.href.split('?');
if (keys[1].match(/(fix|fish|fx)/))
{
$("#linkdiv").append(nextLink);
$("#linkdiv1").append(nextLink);
$("#linkdiv2").append(nextLink);
}
demo button showing : http://jsfiddle.net/LbKmf/show/?fx=shipment+toys/fish-fix-fx/
demo button not showing: http://jsfiddle.net/LbKmf/show/?reigel
Is this what your looking for:
"?fx=shipment+toys/fish-fix-fx/".split(/[\?=+\/-]/g);
window.location.search and split into array for comparisons
explained in How can I get a specific parameter from location.search?
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
Generally, Javascript doesn't have a built-in functionality for query string parameters. You can use string manipulation on window.location.search to get your parameters out of the URL string. Note that location.search includes the ? character too.
Something like this should do:
var queryString = function () {
// Anonymous function - executed immediately
// get rid of the '?' char
var str = "?fx=shipment+toys/fish-fix-fx/";
var query = str.substring(str.lastIndexOf('=')+1,str.indexOf('/'));
var vars = query.split("+");
for (var i=0;i<vars.length;i++){
console.log(vars[i]);
}
return vars;
} ();
var search_name = location.search;
if (search_name.search("cate_no=24") > 0) {
$(".cate_new a").addClass("active");
}
});
If current document url is http://abc.com/list.html?cate_no=24,
I want to add class "active" into li a.
I searched and found these js code, but it doesn't work.
Is it wrong?
It's incorrect. search() returns the offset position of a match if a match is found, and -1 if a match isn't found.
As you are checking for whether cate_no=24 contains cate_no=24, it will return 0 if true.
Currently, your conditional checks whether the search() will return > 0, which is not what you want.
What you should be doing is check whether it is greater > -1:
if (search_name.search("cate_no=24") > -1)
Although, as I mentioned in the first revision of my answer, it would be better and faster to use indexOf() (search() is supposed to be used when dealing with regular expressions, not for simple string searches).
if (search_name.indexOf("cate_no=24") > -1)
search will only gives you the String. that will be in your case ?cate_no=24
So we leave the first part as it is and try to find the desired value in search_name as string.
var search_name = location.search;
This how we can find the index of the desired pattern.
if (search_name.indexOf("cate_no=24") > 0) {
$(".cate_new a").addClass("active");
}
My personal blog is static so I also had to figure out how to do this without PHP or some other server side code.
This bit of code grabs the path of the current URL, e.g. if you are on http://example.com/about, it would return the string '/about/'. From there you write a simple conditional to add a class to the link you select.
var currentURL = window.location.pathname.toString();
console.log(currentURL);
if (currentURL = '/about/') {
$('a#about').addClass('active')
} else if (currentURL = '/work/') {
...
}
This could be further developed to grab the href attributes from an array of links with a certain class (.nav-items, for example) and add the active class to whichever element has a href equal to the returned string.
I am in need of two regular expressions.
First of all I want to check if my URL contains the hashtag #videos. Then if it does, I want to get the value of the second #tag. That value could contain all kinds of characters;
http://local/default.php#videos#12345
http://local/default.php#videos#g5458f
http://local/default.php#videos#0-e4a5d
This is what I've got so far:
if (window.location.hash = 'videos') {
var url = window.location.hash,
id = url.match(regex-goes-here); // output e.g string '12345'
}
(Not sure if my extremely simple check (window.location.hash = 'videos') will work on two hashtags..? There is probably a better way of checking the URL, if so, please do tell :-)
You can get an array of tags like this:
var tags = window.location.hash.replace(/^#/, '').split('#');
In case of http://local/default.php#videos#12345, tags[0] will be videos and tags[1] will be 12345. You can use tags.length to determine how many tags there are.
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.