show alert msg if location.search is missed by javascript - javascript

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)

Related

Javascript how to narrow down suitable URL in the if statment

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

script for on load alert box based on url

I am creating a submittal form, sending the form to a php form, and after the form completes having it redirect to the initial page with an additional "?s=1" in the url.
Basically what I am trying to do is create an alert box pop up on loading the page with the "?s=1" in the url.
It is a very brute force method to use I know, but i can't seem to get the small script to work correctly. I know for certain everything works and loads to the point and reloads the initial page with ?s=1 in it.
Here is the code i'm using to try and prompt the alert box
enter code here <script type="text/javascript">
var Path = window.location.href;
if (Path == "mywebsite.html?s=1")
{
alert("Your Form Has Been Submitted.")
}
else()
{
}
</script>
Does anybody know why the box will not appear? Or possibly an alternate method for what I am attempting to do? Thanks.
window.location.href contains the complete URL, including the domain, and the full path, so a basic equality comparison won't work unless you're exaclty matching it, and even still this could cause problems (e.g. www. versus a naked domain, https:// versus http://, etc.). A possible solution is to use RegEx.
var pathRegex = /mywebsite\.html\?s\=1/;
if (pathRegex.test(window.location.href)) {
alert("Your Form Has Been Submitted.")
}
As a note, you can have an if statement without an accompanying else, and else statements don't take any arguments in parentheses like if, unless you're talking about else if.
Here is some code I wrote up for one of my projects that lets you pull a parameter and value out of the url.
function GetURLParameter(urlParameter){
var url = window.location.search.substring(1);
var urlVariables = url.split('&');
for (var i = 0; i < urlVariables.length; i++){
var parameter = urlVariables[i].split('=');
if (parameter[0] == urlParameter){
return parameter[1];
}
}
}
It's easy to use:
For mywebsite.com?s=1
It would just be
var k = GetURLParameter('s');
if (k == 1){
alert("Your Form Has Been Submitted.")
}
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, " "));
}
And then check like...
if (getParameterByName("s")=="1")
{
alert("Your Form Has Been Submitted.")
}
else
{
}

How to get the page URL in Javascript and call script?

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/

JQuery Detect If in Homepage and Homepage PLUS url Variables

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

How to detect whether a string is in URL format using javascript?

I think the question title seems to explain eveything.
I want to detect whether a string is in URL format or not using javascript.
Any help appreciated.
Try this-
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
usage: if (isUrl("http://www.page.com")) alert("is correct") else
alert("not correct");
function IsURL(url) {
var strRegex = "^((https|http|ftp|rtsp|mms)?://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+#)?" //ftp的user#
+ "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
+ "|" // 允许IP和DOMAIN(域名)
+ "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
+ "[a-z]{2,6})" // first level domain- .com or .museum
+ "(:[0-9]{1,4})?" // 端口- :80
+ "((/?)|" // a slash isn't required if there is no file name
+ "(/[0-9a-z_!~*'().;?:#&=+$,%#-]+)+/?)$";
var re=new RegExp(strRegex);
return re.test(url);
}
Debuggex Demo (Improved version which matches also 'localhost')
try something like this:
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)? (\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
One for the future using the URL constructor and a basic try catch statement, it is supported in most modern browsers. Obviously no IE support...
const isUrl = (str) => {
try {
new URL(str);
return true;
} catch () {
return false;
}
}
If the URL is valid it will get parsed by the constructor and return true.
If the string is not a valid URL the constructor will chuck a syntax error that will get caught and return false.
Try this code. This expression is more complete and takes into account IP address:
function checkUrl(s) {
var regexp = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]#!\$&'\(\)\*\+,;=.]+$/
return regexp.test(s); }
You can use a regular expression for checking the string
^s?https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\#&=+\$,%#]+$
Regular Expressions and Javascript
Had the same task, but all of regex that I found online to check validity of a URL were failed in some test cases.
Here is the regex that worked everything:
/^(http:\/\/www\.|https:\/\/www\.|www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?/
However, If the URL was like: google.com It accepted it as valid (which in my specific case, was considered as invalid)
It worked the best I had found. Worked like a charm!
When given the option, I prefer the simplest solution.
Use _.startsWith(string, 'http') if:
You don't mind if URL is invalid
You're sure the URL being checked will always start with 'http'
You don't expect the string to be another value that might start also with 'http'

Categories

Resources