So basically, I want to only call some script if the URL does not equal blogs.html
For example, these parameters should NOT call the script:
mydomains.com/blogs
mydomains.com/blogs.html
This parameters should call the script:
mydomains.com/blogs/child-page.html
mydomains.com/blogs/another-page
mydomains.com/blogs.html/testin-page.html
mydomains.com/page.html
mydomains.com
I have attempted something like this, although it does not seem to work since blogs.html and blogs are still within the URL.
if(!document.URL.indexOf("blogs.html") >= 0 && !document.URL.indexOf("blogs") >= 0)
{
other script here
}
Is there any way that I can fix this?
First get the pathname, then use the substring method to get everything after the last "/".
var pathName = window.location.pathname;
var pageName = pathName.substr( pathName.lastIndexOf("/") + 1 );
if( pageName != "blogs.html" && pageName != "blogs" ) {
// do something.
}
if(!document.URL.endsWith("blogs.html"))
{
// code here
}
string has endsWith() methods to accomplish this goal
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FString%2FendsWith
or use a regular expression: $
if(!document.URL.search(/(blogs.html)$/) != -1)
// return -1 means a string is not end with blogs.html
{
// code here
}
http://jsfiddle.net/rchMe/
Related
I am trying to develop a Javascript code which will suit my website. Here is my code:
jQuery('.hestia-title').click(function() {
var link;
link = location.href;
if (link = "http://www.puslapioguru.eu" || "https://www.puslapioguru.eu" || "www.puslapioguru.eu") {
var element_to_scroll_to = jQuery('.second-title')[0];
console.log("Viskas veikia");
element_to_scroll_to.scrollIntoView();
} else {
window.location.href = "http://www.puslapioguru.eu/";
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This code should determine on what open page it is run, but I encounter a problem with the if statement:
if (link="http://www.puslapioguru.eu" || "https://www.puslapioguru.eu" || "www.puslapioguru.eu")
I want that the if statement would run only if the specific URL would be opened, but now it even runs if the opened page URL is "http://www.puslapioguru.eu/temu-portfolio/". Can someone please help me with this problem?
Each part of || (or &&) has to equate to true/false by itself, ie:
if ((true|false) || (true||false))
so, rather than just use a string, you need to provide something to compare with, in each of the parts around the ||
Secondly, in javascript, if you are comparing a value you need to use == or ===, not =. This gives,
link = location.href;
if (link == "http://www.puslapioguru.eu"
|| link == "https://www.puslapioguru.eu"
|| link == "www.puslapioguru.eu") {
You can make this more flexible, but these are the essential issues with your if.
In this case you might want just location.host instead of location.href as .href is the entire address including any page path or parameters while .host already removes the https:// etc parts for you:
link = location.host;
if (link == "www.puslapioguru.eu") {
Either use a Regular Expression
/^https?:\/\/(?:www\.)?puslapioguru\.eu$/i.test(link); // Exactly on this
// OR
/^https?:\/\/(?:www\.)?puslapioguru\.eu(?:$|\/)/i.test(link); // Any path on this
Or use Array methods to test for your options
const permittedSiteList = [
'http://www.puslapioguru.eu',
'https://www.puslapioguru.eu',
'www.puslapioguru.eu'
];
permittedSiteList.includes(link); // eactly one of these
// OR
permittedSiteList.some(
domain => (link + '/').toLowerCase().startsWith(domain + '/')
); // Any path
If you choose one of these, I also recommend abstracting the RegExp or the Array outside the condition so it is more readable; i.e. the if's condition looks like
if (permittedSiteRegExp.test(link)) {
// ...
}
// OR
if (permittedSiteList.includes(link)) {
// ...
}
// OR in the Array + any path case, also the test function
const isThisDomain = domain => (link + '/').toLowerCase().startsWith(domain + '/');
if (permittedSiteList.some(isThisDomain)) {
// ...
}
Currently, you're performing an assignment in your if statement so you'll get unexpected behaviour
So I have paths such as "/users/2" or "/users/4" or "/users/25" etc and I need to setup an if statement such as:
if(window.location.pathname == "/users/?????") {};
that catches all of these paths.
you could check the indexOf of '/users/'
var pathName = window.location.pathname;
if (pathName.indexOf('/users/') === 0) {
}
I guess if you have just "/users/", and nothing after the 2nd slash your condition would be not satisfied, I suggest something to ensure you have the id of the user (checking the length of the string to be greather than --> the position of the substring to search AND its length added, if it's so --> there must be something after it, which we suppose it's the id...) like this:
var p = window.location.pathname;
if(p.indexOf("/users/") > -1 && p.length > p.indexOf("/users/") + 7) {
...
}
...maybe you can also check if the id after the 2nd slash is a number if needed...
Please use this:
var pathname = window.location.pathname;
if (pathname.startsWith('/users/')) {
// Do stuff here
}
Read more about startsWith method.
the page url is example.com/1/page.html?user=123456
need to check if the current page url contains
example.com/1/page.html
without
?user=123456
because this is dynamic variable
show alert msg hello .. by javascript check current url
if ( window.location.href = "example.com/1/page.html") {
alert("hello");
}
but not working
another idea !!
Well window.location.href is a string so you could treat it as such and do some manipulation to remove the query part of the URL ( ? bit ) or you could look into a string contains function.
Look into JS indexOf() or split()
use pathname
if ( window.location.pathname = "/1/page.html") {
alert("hello");
}
You can use window.location.pathnameinstead ofwindow.location.href`
That'll give you just the path
if ( window.location.href = "/1/page.html") {
alert("hello");
}
I'd do (split the string on ?, should not break if none) :
if (window.location.href.split("?")[0] === "example.com/1/page.html") {
alert("hello");
}
Comparison is made with == or === not = (assignment)
window.location.href = "example.com/1/page.html" means window.location.href takes the value "example.com/1/page.html" (don't even know if you can write this property)
I am using this code to detect the homepage and it works great:
var url= window.location.href;
if(url.split("/").length>3){
alert('You are in the homepage');
}
My problem is that I also need to detect if the url has variables for example:
mysite.com?variable=something
I need to also detect if the url has variables on it too
How can I do this?
Using window.location.pathname could work too:
if ( window.location.pathname == '/' ){
// Index (home) page
} else {
// Other page
console.log(window.location.pathname);
}
See MDN info on window.location.pathname.
You can find out if you're on the homepage by comparing href to origin:
window.location.origin == window.location.href
To get the query parameters you can use the answer here:
How can I get query string values in JavaScript?
Take a look at the window.location docs , the information you want is in location.search , so a function to check it could just be:
function url_has_vars() {
return location.search != "";
}
if current url is xxxxx.com something like that, then xxx
if (window.location.href.split('/').pop() === "") {
//this is home page
}
You need a query string searching function to do this..
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Before redirect check the query string and match with the expected value and redirect as requirement.
Taking inspiration from Mataniko suggestion, I slightly modified it to fix its issue:
if (window.location.origin + "/" == window.location.href ) {
// Index (home) page
...
}
In this way, this test pass only in homepage
I am adding a Search feature, and if the user is on the search results and they refresh the page I want it to stay at that search. I already put the search query into the URL, but I don't know how to retrieve it. It will most likely require a regexp so anyone that is experienced with regexp, please help.
Here is how I put it into the URL:
function trimspace(str) {
str = str.replace(/ +(?= )/g, '');
return str;
}
function searchMail() {
var query = trimspace($('#search_input').val());
if (query == '' || !query || query == null) {
$('#search_input').focus();
}
else {
window.location.hash = '#!/search/' + query;
$('#loader').show();
$.get('tools.php?type=search', { q: query }, function(data, textStatus) {
$('#loader').hide();
if (textStatus == 'success') {
hideAllTabs();
$('#search_results').html(data).show();
document.title = "Search results - WeeBuild Mail";
}
else {
alertBox('Search failed. Please try again in a few minutes.', 2500);
}
});
}
}
And besides just retreiving the query I need to be able to detect if the hash is #!/search/query.
Thanks in advance!
Detect if query is #!/search/query:
location.hash==='#!/search/query'
Finding out about the query parts assuming the query is #!/search/query:
var parts = location.hash.split('/');
parts[0] is #!. parts[1] is search and parts[2] is test. Doing with the parts want you want should now be trivial enough.
In response to the comments:
function getPartAndRemainder(){
var parts = location.hash.split('/');
if(parts[0]!=='#!' || parts.length<2){
// Value after # does not follow the expected pattern #!/part/any_parameters
throw new Error('Cannot parse application part.');
}
return {
// Contains the part of your application (word after first slash after #)
part: parts[1],
// Contains everything after second slash after # or the empty string
remainder: location.hash.substring(
// Length of #! (or whatever somebody might use instead)
parts[0].length
// Length of first slash
+1
// Length of your application part's name
+parts[1].length
// Length of the second slash
+1)
};
}
The function gives back an object that contains the part of your application at the key part and the remainder key will contain the rest. So, if your URI would be something#!/search/test the function would return {part:'search', remainder:'test'}.
In case the URI can't be parsed, you'll get an error and you should then use a sensible default instead.
You would use the method as follows whenever the hash changes or at some other event (point in time) where you are interested in the hash value:
try {
var hashValue = getPartAndRemainder();
if(hashValue.part==='search'){
var query = hashValue.remainder;
alert('You searched: '+query)
}
if(hashValue.part==='inbox'){
alert('You are in inbox, now');
}
} catch(e){
// It was not possible to parse the value after the # from URI according to our expected pattern.
alert('No idea what to do with: '+location.hash);
}
This regex will match anything after the search param, is this what you are looking for?
/#1/search/(.*)/
var match = /\/.*\/.*\/(.*)\//i.exec(location.hash)
//match contain the query