How to ignore extra parameters in URL? - javascript

< noob >
This following code works like a charm when I use the proper URL
www.exemple.com/?login
$(document).ready(function(){
function urlparam(){
var url = window.location.href.split('?')[1];
if (url == 'login' ) {
document.getElementById('loginMainContainer').style.display = 'block';
$('.login').triggerHandler('click');
} else if (url == 'signup' ){
document.getElementById('loginMainContainer').style.display = 'block';
$('.signup').triggerHandler('click');
}
}
urlparam()
});
But once I need to use this URL with other parameters (w/ mailchimp)
www.exemple.com/?login&utm_source=App+Accounts&utm_campaign=e94f95d4da-News_promo+email_English_2016
It really doesn't execute what I need.
Is there a way to ignore these extra parameters and execute properly my function?
Thanks for any help in advanced!
< /noob >

I would use a regular expression to handle this, it tests to match if the string starts with login or if it starts with signup.
var url = ('www.exemple.com/?login&utm_source=App+Accounts&utm_campaign=e94f95d4da-News_promo+email_English_2016').toString().split('?')[1];
if (url.match(/^login/ )) {
console.log('login');
} else if (url.match(/^signup/ )){
console.log('signup');
}

You just have to get all parameter and check if login exist.
var url="http://someurl.com?test=ok&machin=1234&login&azir=lol";
function parameterExist(url,paramName)
{
var parameters = url.split('?')[1].split('&');
for(var i=0;i<parameters.length;i++)
{
var paramNameUrl=parameters[i].split('=')[0];
if(paramNameUrl==paramName)
return true;
}
return false;
}
console.log(parameterExist(url,"login"));
console.log(parameterExist(url,"blabla"));

Related

Is there a better way to 'do nothing' in javascript if statement?

My url looks like this = https://studentscafe.com/menu/2
I'm trying to check whether or not it has 2 different url params...
1.) ?dinner=1
or
2.) &dinner=1
If #1 is present, do nothing
If #2 is present, do nothing
But if neither are present, default to adding ?dinner=1 to the url.
Is there a better way to have a default do nothing in an if statement? Fiddle here for example.
var path = 'https://studentscafe.com/menu/2';
if (path.indexOf('?dinner=1') >= 1) {
console.log('has ?');
// do nothing leave url as it is
} else {
console.log('does not have ?');
if (path.indexOf('&dinner=1') >= 1) {
// do nothing leave url as it is
} else {
path = path + '?dinner=1';
}
}
Expected output: if the url doesn't have #1 or #2: https://studentscafe.com/menu/2?dinner=1
Instead of
if (something) {
// do nothing
} else {
// do what you need
}
You can use
if (!something) {
// do what you need
}
In your case:
if (path.indexOf('?dinner=1') == -1 && path.indexOf('&dinner=1') == -1) {
path = path + '?dinner=1';
}
Using a regular expression and the ! negation operator, this can be rather simple:
var path = 'https://studentscafe.com/menu/2';
if (!/[?&]dinner=1/.test(path)) {
path += '?dinner=1';
}
console.log(path);
You can do this way.
var path = 'https://studentscafe.com/menu/2';
// Since there is no change to path if it contains either ?dinner=1 or &dinner=1
if (path.indexOf('dinner=1') >= 1) {
console.log('has dinner');
// do nothing leave url as it is
} else {
path = path + '?dinner=1';
}
In modern JS you may simply do like
['?dinner=1','?dinner=2'].every(s => !path.includes(s)) && (path += '?dinner=1');

JavaScript ternary operator into full if/else statement issue

I have following ternary statement:
$.history.init(function(url) {
load(url == "" ? "#some-page" : url);
});
Which I have rewrote into:
$.history.init(function(url) {
load(
if( url == ""){ url = "#some-page"
} else { url = url }
);
});
I now the is an error on line 3 if(url == ""), but I don't understand what error.
Any suggestion much appreciated.
In JavaScript, an if is not an expression. It does not return a value and cannot be put inside a function call. That is, this is not valid:
func(if (a) { ... } else { ... });
This is the main difference between if and ?:--the operator is an expression and returns a value; if is a statement, does not return a value and cannot be used everywhere.
Your best bet if you have to avoid the ternary operator is to do something like:
if (url == "") {
url = "#some-page";
}
load(url);
You can also achieve the same effect using ||:
function (url) {
load(url || "#some-page");
}
This is the shortest and most idiomatic way to write your code.
if expressions dont return anything in JS. So that basically does load(undefined).
Try this instead:
if (url === '') {
url = '#some-page';
}
load(url);
Note you don't need to else at all, because if the value is present you have nothing to change.
rewrite it as
$.history.init(function(url) {
if( url == ""){
url = "#some-page";
}
load( url );
});
Your rewritten code is invalid. Try this:
$.history.init(function(url) {
if(url == "") {
load("#some-page");
} else {
load(url);
}
});
You need the if statement to be outside of the load function, i.e.
$.history.init(function(url) {
if (url === "") {
url = "#some-page";
}
load(url);
});
Note that you don't need the else clause as url = url is a redundant operation.

use javascript to find parameter in url and then apply if then logic

I am trying to make my page perform an action only if it sees that a particular parameter is present in the url.
I essentially want the javascript code to do this:
consider an example page such as: http://www.example.com?track=yes
If a page loads that contains the parameter 'track' within the url, print 'track exists', else if the 'track' parameter doesn't exist print 'track does not exist'
This should work:
if (window.location.search.indexOf('track=yes') > -1) {
alert('track present');
} else {
alert('track not here');
}
Use something like the function from Artem's answer in this SO post:
if (getParameterByName('track') != '') {
alert ('run track');
}
It's not hard to split up the query string to find the relevant bits:
var path = location.substr(1), // remove ?
queryBits = path.split('&'),
parameters = {},
i;
for (i = 0 ; i < queryBits.length ; i++) {
(function() { // restrict keyval to a small scope, don't need it elsewhere
var keyval = queryBits[i].split('=');
parameters[decodeURIComponent(keyval[0])] = decodeURIComponent(keyval[1]);
}());
}
// parameters now holds all the parts of the URL as key-value pairs
if (parameters.track == 'yes') {
alert ('track exists');
} else {
alert ("it doesn't");
}
What you're looking for is called the Query String or Query Parameter. See this function to get it w/o the use of plugins like jQuery: How can I get query string values in JavaScript?
You can use the window.location.search property:
if(/(^|&)track(&|$)/.test(window.location.search.substring(1))) {
alert('track exists!');
} else {
alert('it doesn\'t...');
}

Checking image name using javascript

I'm changing the img src on click using javascript.
I'm trying to determine whether to switch on or off.
I'm testing the following:
var img_el = document.getElementById("on_off_img");
if ( img_el.src == 'img/on.png' ) {
img_el.src = 'img/off.png'
} else {
img_el.src = 'img/on.png'
}
My problem is that i never get a match - it looks like img_el.src returns the full URL... Is there a function to just test the actual filename instead of the full string to the file?
Or is there a better way to manage the click?
use indexOf() instead of comparing the src
e.g
var img_el = document.getElementById("on_off_img");
if ( img_el.src.indexOf('on.png') > -1) {
img_el.src = 'img/off.png'
} else {
img_el.src = 'img/on.png'
}
Yuo can always use indexOf:
if(img_el.src.indexOf('img/on.png') > -1){
img_el.src = 'img/off.png'
}else{
img_el.src = 'img/on.png'
}
To shorten this even more, you can use a ternary operator:
var img_el = document.getElementById("on_off_img"),
isOn = img_el.src.indexOf('on.png')>-1;
img_el.src = isOn ? 'img/off.png' : 'img/on.png';
You can use match statement aswell.
var img_el = document.getElementById("on_off_img");
if ( img_el.src.match("on.png"))
{
img_el.src = 'img/off.png'
} else
{
img_el.src = 'img/on.png'
}
Try using JQuery:
$("#on_off_img").click(function(){
if($(this)[0].nameProp == "on.png")
$(this).attr("src","img/off.png");
else
$(this).attr("src","img/on.png");
});

Javascript for conditional URL append or redirect based on window.location.href

I am trying to make a bookmarklet that when clicked will check the URL of the current tab/window to see if it contains 'char1' and/or 'char2' (a given character). If both chars are present it redirects to another URL, for the other two it will append the current URL respectively.
I believe there must be a more elegant way of stating this than the following (which has so far worked perfectly for me) but I don't have great knowledge of Javascript. My (unwieldy & repetitive) working code (apologies):
if (window.location.href.indexOf('char1') != -1 &&
window.location.href.indexOf('char2') != -1)
{
window.location="https://website.com/";
}
else if (window.location.href.indexOf('char1') != -1)
{
window.location.assign(window.location.href += 'append1');
}
else if (window.location.href.indexOf('char2') != -1)
{
window.location.assign(window.location.href += 'append2');
}
Does exactly what I need it to but, well... not very graceful to say the least.
Is there a simpler way to do this, perhaps with vars or a pseudo-object? Or better code?
A (sort-of) refactoring of dthorpe's suggestion:
var hasC1 = window.location.href.indexOf('char1')!=-1
var hasC2 = window.location.href.indexOf('char2')!=-1
var newLoc = hasC1
? hasC2 ? "https://website.com/" : window.location.href+'append1'
: hasC2 ? window.location.href+'append1' : '';
if (newLoc)
window.location = newLoc;
Calling assign is the same as assigning a value to window.location, you were doing both with the addition assignment += operator in the method anyway:
window.location.assign(window.location.href+='append2')
This would actually assign "append2" to the end of window.location.href before calling the assign method, making it redundant.
You could also reduce DOM lookups by setting window.location to a var.
The only reduction I can see is to pull out the redundant indexof calls into vars and then test the vars. It's not going to make any appreciable difference in performance though.
var hasChar1 = window.location.href.indexOf('char1') != -1;
var hasChar2 = window.location.href.indexOf('char2') != -1;
if (hasChar1)
{
if (hasChar2)
{
window.location="https://website.com/";
}
else
{
window.location.assign(window.location.href+='append1');
}
}
else if (hasChar2)
{
window.location.assign(window.location.href+='append2');
}
Kind of extendable code. Am i crazy?
var loc = window.location.href;
var arr = [{
url: "https://website.com/",
chars: ["char1", "char2"]
}, {
url: loc + "append1",
chars: ["char1"]
}, {
url: loc + "append2",
chars: ["char2"]
}];
function containsChars(str, chars)
{
var contains = true;
for(index in chars) {
if(str.indexOf(chars[index]) == -1) {
contains = false;
break;
}
}
return contains;
}
for(index in arr) {
var item = arr[index];
if(containsChars(loc, item.chars)) {
window.location.href = item.url;
break;
}
}
var location =window.location.href
if (location.indexOf('char1')!=-1 && location.indexOf('char2')!=-1)
{window.location="https://website.com/";}
else if (location.href.indexOf('char1')!=-1) {window.location.assign(location+='append1');}
else if (location.indexOf('char2')!=-1) {window.location.assign(location+='append2');}

Categories

Resources