jQuery - Only carry out action if url doesn't contain any parametres - javascript

I have a function that runs only if an attribute is blank:
if (!$(".main-image").attr("src")) {
loadImageAjax();
}
But I also only want it to run IF the url doesn't contain any parametres.
So only if the domain is simply: www.domain.com and not www.domain.com/?image=33

You can check for the existence of the ? character. More often than not, if there are going to be url parameters, the ? character will also exist.
if ( url.indexOf("?") < 0 ) {
// code for 'no parameters' goes here
}
If your URLs use a different pattern you will need a function that knows how to check where the parameters are. (Stack Overflow URLs are an example of URLs that do not follow the ?a=1&b=2 pattern).
If you want to disallow everything that is not "www.domain.com", you can check for the existence of the "/" character.
var indexOfSlash = url.indexOf("/");
// the second check is just in case you want to allow "www.domain.com/"
if ( indexOfSlash < 0 || !url.substring(indexOfSlash + 1) ) {
// code for 'no parameters' goes here
}

Related

Get part of a url in javascript before the parameters

I've a url ('https://xyz.abc.org.com/v1.5/wth/data/analysis/geo?run=run1&aaa=some') which remains the same till 'v1.5' till any api calls.
So I need to get the last part 'geo' out of the url.
Here's my code:
var testUrl = 'https://xyz.abc.org.com/v1.5/wth/data/analysis/geo?run=run1&aaa=some';
console.log(testUrl.substring(testUrl.lastIndexOf('/')));
But, this returns - 'geo?run=run1&aaa=some', while I want 'geo'.
How do I fix this?
Also, I can't use some numbers to get the substring out of it, as that part of the url will be different for different api calls.
I just need the part of the url after last '/' and before '?' or '&'.
Last index of / and first index of ?. In between these is the text you require
var testUrl = 'https://xyz.abc.org.com/v1.5/wth/data/analysis/geo?run=run1&aaa=some';
console.log(testUrl.substring(testUrl.lastIndexOf('/')+1, (testUrl.indexOf('?') > testUrl.lastIndexOf('/') + 1)) ? testUrl.indexOf('?') : testUrl.length );
// prints geo
This will work whether there is a parameter list or not:
testUrl.substring(testUrl.lastIndexOf('/')+1, testUrl.indexOf('?') > 0 ? testUrl.indexOf('?') : testUrl.length)
Why not just get rid of everything starting from the question mark? You can modify the string you already have.
var testUrl = "https://xyz.abc.org.com/v1.5/wth/data/analysis/geo?run=run1&aaa=some";
var extractWithParams = testUrl.substring(testUrl.lastIndexOf('/'));
var extractWithoutParams = extractWithParams.split("?")[0];
console.log(extractWithoutParams);
// you could just do in all in one go,
// but i wrote it that way to make it clear what's going on
// testUrl.substring(testUrl.lastIndexOf('/')).split("?")[0];
Alternatively, you could also try
var extractWithParams = testUrl.substring(testUrl.lastIndexOf('/'));
var n = extractWithParams.indexOf("?"); // be careful. there might not be a "?"
var extractWithoutParams = extractWithParams.substring(0, n != -1 ? n : s.length);
I'm not sure which one performs better, but I'd imagine that the first one might be slower since it involves array operations. I might be wrong on that. Either way, if it's a one-time operation, the difference is negligible, and I'd go with the first once since it's cleaner.

return true if only there is exact include

Using includes method we get true for all of these logs:
console.log("https://example.com/test/media/instructions/listen_again_long/1.mp3".includes('listen_again_long')); // true
console.log("https://example.com/test/media/instructions/listen_again_long/2.mp3".includes('listen_again')); // true
console.log("https://example.com/test/media/instructions/listen_again_long/3.mp3".includes('listen')); // true
But we know only the first log should return true because we have exactly listen_again_long inside the longer string.
if we consider this part fixed: https://example.com/test/media/instructions/
How we can only return true for the first one and false for the rest of the logs?
You are actually looking for a certain string enclosed in /, so one option would be to simply include both / in the argument you are passing to String.prototype.includes():
console.log("https://example.com/test/media/instructions/listen_again_long/1.mp3".includes('/listen_again_long/'));
console.log("https://example.com/test/media/instructions/listen_again_long/2.mp3".includes('/listen_again/'));
console.log("https://example.com/test/media/instructions/listen_again_long/3.mp3".includes('/listen/'));
You could also do the same thing using RegExps and RegExp.prototype.test():
console.log(/\/listen_again_long\//.test("https://example.com/test/media/instructions/listen_again_long/1.mp3"));
console.log(/\/listen_again\//.test("https://example.com/test/media/instructions/listen_again_long/2.mp3"));
console.log(/\/listen\//.test("https://example.com/test/media/instructions/listen_again_long/3.mp3"));
In both cases you could replace /listen_again_long/ with the whole thing if you want to make sure the match doesn't happen in a different place:
"...".includes("https://example.com/test/media/instructions/listen_again_long/");
Or, with RegExp:
/https:\/\/example.com\/test\/media\/instructions\/listen_again_long\//.test("...");
You'll have to extract the substring you want to compare against your parameter and then do a straight === comparison.
var url = <your passed in mp3 file>;
var s = "https://example.com/test/media/instructions/"
var substring = url.substring(url.indexOf(s) + url.length);
substring = substring.substring(0, url.indexOf("/");
substring === "listen_again_long"

javascript: How to show a message using an alert after Ajax request

I am trying to display an alert after an Ajax request has been submited successfully.
$.post(
"ajax_request.php", {
email: email
},
function(data) {
$('#message').html(data);
var y = $('#message').text();
if (y == 'exists') {
alert('text');
}
);
The script above works, but I cannot display the alert, although the var y contains the word exists.
Change to this:
if(y.indexOf('exists') != -1){
alert('text');
}
If you wish to check if one string contains another, use the following code:
if (y.indexOf('exists') > -1) {
alert('test');
}
Reading Material
indexOf()
== is used for comparing if two variables are equal or not. It doesn't check data type.
=== is used for comparing two variables if they are equal as well as their data type is same.
In your case, you don't have to use any of them because you need to check whether a string contains a substring or not.
To check whether a string contains a particular substring or not, you need to use indexOf().
Now, Assuming that you are getting some data as the response and somehow storing it in variable y.
Now, to check whether y contains word 'exists' or not, you should check it the following way.
if(y.indexOf('exists) != -1) {
//do something
}
Let's define y and check
var y = "Does this sentence contain word exist?";
y.indexOf('exist');
Output : 32
If y doesn't contain exist, then the output would have been 1.

If Statement Have A String And Other String (Make To List)

Sorry i cant find the tutorial in google because i dont know the keyword...
var currentURL=location.href;
var str = currentURL;
if(str == "http://web.com/blabla" || str == "http://web.com/bleble"){
window.location = "http://web.com/ban";
} else {
}
How to make str == "http://web.com/blabla" || str == "http://web.com/bleble" to list ? so if i want to input some url again, i just input the url to the list. Can give me the code or link tutorial ???
Basically you'll need to place all of your URL's into an array and then iterate over the array checking each item.
var urls = ['http://web.com/','http://web.net/','http://web.org'];
var current_url = '...';
for (var i = 0; i < urls.length; i++){
if (current_url == urls[i]){
window.location = "http://web.com/ban";
break; // exit the loop since we have already found a match
}
}
The break command will terminate the loop and stop searching the array for matching URLs. Since the action you want to take needs to happen if any of the URLs match, it's enough for one to match in order to stop searching.
Lists are called arrays in javascript, and are declared using square brackets, like this: var badUrls = ["http://web.com/blabla", "http://web.com/bleble"].
To check whether the current URL appears in the array, you can use the .indexOf function of the array, which will return the first position in the array where the string you provide can be found (starting with 0 for the first element), or -1 if it doesn't exist. For example, if you have an array var arr = ["foobar", "foo", "bar", "baz"], and you do arr.indexOf("foo"), you get 1 because it's the 2nd element in the array. If instead you do arr.indexOf("fooba"), you will get -1 because none of the elements in the array are fooba exactly. In your code, you want to redirect the user if badUrls.indexOf(str) > -1. You can get more information on indexOf in the MDN Documentation.
That makes your code look like:
var currentURL=location.href;
var str = currentURL;
var badUrls = ["http://web.com/blabla", "http://web.com/bleble"]
if(badUrls.indexOf(str) > -1){
window.location = "http://web.com/ban";
} else {
}
window.location is a browser object, it you want the page to go to http://web.com/ban, you should use
window.location.href = "http://example.com/ban";
However, it looks like you are trying to prevent people from visiting pages using JavaScript. This is extremely insecure, because anyone that lists your code will see which URLs you're trying to protect and immediately request them. If they request those URLs with JavaScript disabled, or using curl, the pages will be delivered.
You should protect the pages with server side configuration. With Apache, you can use the Allow/Deny configuration or RewriteRules.

JS - What is the difference here?

I'm a newbie to JS and it would be extremely useful to know what the differenece is between the following two if statement conditions...
First condition (not actually working):
if ( window.location.pathname == '/#register' ) {
// Code
}
Second condition:
if (document.URL.indexOf("#register") >= 0) {
// Code...
}
FYI, this would help me solve a bug I'm experiencing here
The first checks for an exact match. And it does it on the pathname, which doesn't include the hash, so it probably doesn't do what you want.
The second one checks the string contains "#register", so the full path could be bigger, like /#register_or_not or /some/other/path#register
Probably your best option would be to do a regex pattern match on the URL, to ensure that the hash it matches is ONLY 'register', while allowing the rest of the URL to be whatever:
if (document.URL.match(/.*#register$/)) {
The second just check if the url contains #register, the first the url path, you can do it also with location.hash
if(location.hash=='#register') { //....
The first one performs an exact match between window.location.pathname and /#register. The second one looks for #register anywhere in document.URL.
This if block check the strings whether they are equal or not
if ( window.location.pathname == '/#register' ) {
// Code
}
The indexOf() method returns the position of the first occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
if (document.URL.indexOf("#register") >= 0) {
// Code...
}

Categories

Resources