How to know if a url has parameters in javascript - javascript

I want to check if a url has parameters or it doesn't, so I know how to append the following parameters(with ? or &). In Javascript
Thanks in advance
Edit:
With this solution it works perfectly:
myURL.indexOf("?") > -1

Split the string, and if the resulting array is greater than one and the second element isn't an empty string, then at least one parameter has been found.
var arr = url.split('?');
if (arr.length > 1 && arr[1] !== '') {
console.log('params found');
}
Note this method will also work for the following edge-case:
http://myurl.net/?
You could also match the url against a regex:
if (url.match(/\?./)) {
console.log(url.split('?'))
}

Just go through the code snippet, First, get the complete URL and then check for ? using includes() method.includes() can be used to find out substring exists or not and using location we can obtain full URL.
var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url = window.location.href; // Returns full URL (https://example.com/path/example.html)
var origin = window.location.origin; // Returns base URL (https://example.com)
let url = window.location.href;
if(url.includes('?')){
console.log('Parameterised URL');
}else{
console.log('No Parameters in URL');
}

You can try this:
if (url.contains('?')) {} else {}

You can try this also.
var url = YourURL;
if(url.includes('?')) {} else {}
url.includes('?') Will return true if ? exist in the URL.

Related

Regex check against referrer URL string

var orig = document.referrer; // Incoming URL
var check = new RegExp("boxes", "gi"); // Literal string, global + case insensitive.
// console.log(check);
if (orig.indexOf(check) > -1) {
console.log('you came from the box section');
} else {
console.log('you DIDNT come the box section');
}
Hi Guys,
I have a 'boxes' category on a site, where all box items have 'boxes' in the URL. A particular item from another category needs to be able to check whether or not the user came from a 'boxes' item. (This is an interim solution as I only have skin-level access).
When logging 'check', I get '/boxes/gi', which should be working when checking within indexOf, as a valid regex string.
I am not too sure why I can not get this to properly check, as the result is only ever that the user didn't come from the 'boxes' section.
I have a lot to learn, so in advance, I greatly appreciate any help.
Thanks!
You can use string variable instead of regex
var orig = document.referrer; // Incoming URL
// console.log(check);
if (orig.indexOf("boxes") > -1) {
console.log('you came from the box section');
} else {
console.log('you DIDNT come the box section');
}
indexOf does not accept a regex as argument. You either use your regex with search, or use indexOf with a string.
orig.toLowerCase().indexOf("box") > -1
// or
orig.search(check) > -1
You can parse the referrer URL into a link element and retrieve its pathname. You should also probably check the hostname to make sure it's from your own site:
var url = document.createElement('a');
url.href = document.referrer;
var comingFromBoxes = url.hostname === 'yoursite.com' && url.pathname.indexOf('/boxes') === 0;
Note: the referrer is not a reliable value by any means and should not be considered as such.
You can use match() with the regex to perform your logic.
$(document).ready(function(){
var url = "www.someurl.com/boxes/gi/abc";
var regex = /\/boxes\/gi/g;
var mtch = url.match(regex);
if(mtch !== null){
alert('url has the value');
}
else{
alert('url does not have the value');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Trying to redirect to the same page but with querystring value

I want to redirect to the same page, but add some querystring values.
If there is already a querystring value, I want to strip it out and add a new one.
My code isn't working currently, not sure why:
var url = window.location.href;
if(url.indexOf("?") > 0) {
url = url.substring(0, url.indexOf("?"));
} else {
url += "?joined=true";
}
window.location.replace(url);
The problem is that you're not adding the new query string when you strip off the old one, only in the else clause when there's no old query string. Take that addition out of the else, so you do it all the time.
var url = window.location.href;
if(url.indexOf("?") > 0) {
url = url.substring(0, url.indexOf("?"));
}
url += "?joined=true";
window.location.replace(url);
It would be better to use the already-available URL API.
var url = new URL(window.location.href);
url.searchParams.set('joined', true);
window.location.replace(url.toString());
You can check the following links to learn more about it:
https://developer.mozilla.org/en/docs/Web/API/URL
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

How to check if string contains '?' using javascript

I'm trying to check if an url contains a query string or not.
Lets say we have these two url's.
http://localhost:3000/userbookings/list
http://localhost:3000/userbookings/list?resource=de
My string is called fullPath, and I need to check if it contains the ?, so I know if its a query string or not.
Have tried with the following code:
if (fullPath.indexOf("?") > -1){
content = fs-readFileSync('http://localhost:3000/userbookings/list1');
}
else {
content = fs.readFileSync(fullPath);
}
Your way should work too but if you want in the future to use more complex qualifiers you could start using regular expressions:
var pattern = /\?/g;
var found = fullPath.match(pattern) != null;
alert(found);
this help you :
<html>
<head>
</head>
<body>
<script>
var str = "this is ?text";
var patt = /\?/gi;
if(str.search(patt)!=-1)
alert("Found");
else
alert("No found");
</script>
</body>
</html>
Like this:
if (str.indexOf("?") >= 0)
Or,
if (/\?/i.test(str))
Or,
if(str.includes('?'))
Please note that String.includes is an EcmaScript 6 feature and may not work in some browsers.
I think your goal is just to check if there's a php get variable right??
if(document.localtion.search != "") {
// Your code
}
The document.location.search will be "?resource=de" if you visit the url
http://localhost:3000/userbookings/list?resource=de
And it will be "" if you visit the url
http://localhost:3000/userbookings/list
Answer #2
check = document.location.split("?");
if(check.length > 1) {
//do your code
}
splitting the http://localhost:3000/userbookings/list?resource=de url using "?" will be splitted by 2.
And splitting the http://localhost:3000/userbookings/list url using "?" wil result by 1.
Answer #3
check = fullpath.replace("?","");
if(check != fullpath) {
//do your code
}
Removing the "?" in the full path. If the check is the same as fullpath then it doesn't have a "?"
I think this might help you out. Feel free to comment

Javascript say if a folder is child of another

I have these strings which are addresses of files and folder:
../../../folder1/sub1/sub12/
../../../folder1/
../../../another-folder/
I want to compare them using javascript - possibily jquery - to see if for example string 1 have a part egual to string 2 but something more saying that string 1 is child of string 2.
How can i do this?
you could try something like the following
var path1 = "../../../folder1/";
var path2 = "../../../folder1/sub1/sub12/";
if (path2.indexOf(path1) != -1){
//path2 is a sub of path 1
}
In case your string can contain also absolute paths or paths containing .. not only at the beginning I would recommend checking if .indexOf return 0 instead of anything that is not -1.
It can help with cases like.
var path1 = "/rootFolder/";
var path2 = "../folder/rootFolder/";
if (path2.indexOf(path1) === 0) {
console.log("You want this"); // won't get executed => good
}
if (path2.indexOf(path1) !=-1) {
console.log("You don't want this"); // will get executed => bad
}
if(string1.indexOf(string2) != -1){
//string2 is present in string1
}
else{
//string2 is not present in string1
}
You can use the indexOf method to find whether one string is a part of another string.
From w3schools documentation:
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.
var test = "../folder/subfolder1";
var test2 = "../folder";
if (test.indexOf(test2) !=-1) {
alert(test + " is a subfolder of " + test2);
}

Using jQuery, how I can get the file portion of the URL?

How I can get the URL portion of an URL using jQuery?
I have this URL: http://127.0.0.1/deposito/site/main/lojas.php. How I can get lojas.php?
You can use JavaScript and a regex to retrieve the file name like this:
function GetFilename(url){
if (url){
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1){
return m[1];
}
}
return "";
}
The above solution is more comprehensive, but something as simple as this would work in the majority of cases:
var filename = url.match(/.*\/(.+?)\./);
If you need to use jQuery, you can use the jQuery-URL-Parser plugin:
var file = $.url.attr("file");
Here's a link to the plugin:
https://github.com/allmarkedup/jQuery-URL-Parser
JavaScript:
var pathParts = window.location.pathname.split("/");
var file = pathParts[pathParts.length - 1];
alert(file);
If it's the document's current URL, you can "split-pop" document.location.pathname:
alert(document.location.pathname.split("/").pop());
//-> "lojas.php"
Otherwise, if you have the URL in a string you will need to remove any hash or query strings:
var url = "http://127.0.0.1/deposito/site/main/lojas.php"
alert(url.replace(/(?:\?|#).+/, "").split("/").pop());
//-> "lojas.php"

Categories