Current page URl check by JavaScript - javascript

I have tried to check the URL by this function. If we use single text then its working, but when we put the URL it's not working.
jQuery(document).ready
(
function ()
{
//var regExp = /franky/g; //It's working
var regExp = /http://localhost/sitename/members/g; //its not working
var testString = "http://localhost/sitename/members/alan/course/";//In your case it would be window.location;
var testString = window.location;//Inyour case it would be window.location;
if(regExp.test(testString)) // This doesn't work, any suggestions.
{
alert("your url match");
}else{
alert("Not match");
}
}
);

You mention the wrong regex in your code,
var regExp = /http://localhost/sitename/members/g;
Here you will get a syntax error.
Instead of this, you can use regex like,
var regExp = new RegExp("http://localhost/sitename/members");
OR
var regExp = /http:\/\/localhost\/sitename\/members/g;

According to your question, what i understand is that your only goal is to check the url if it contain specific string or not. For that purpose you dont need a Regex. You can use JS include function to achieve your desired result.
jQuery(document).ready
(
function ()
{
var check_string = "localhost/sitename/members";
var test_string = "http://localhost/sitename/members/alan/course/";
if (test_string.includes(check_string))
{
alert("your url match");
}
else
{
alert("Not match");
}
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Related

How to match specific URL in JavaScript or jQuery?

I would like to match the specific URL like "http://www.google.com" in JavaScript
var str = "http://wwww.google.com"
var test = match(str)
if(test) {
alerT(match with the url)
}
Please suggest me how to do it.
If you want to test if the variable matches the specific url, you can use a simple expression.
var str = "http://wwww.google.com";
if(str == "http://wwww.google.com"){
alert('string matches');
}
It can be http or https, so better to verify the URL in two steps:
var str = "http://www.google.com";
var protocol = str.match(/http/gi);
if (protocol != null){
var url = str.match(/wwww.google.com/gi);
if(url != null){
//Do your work
}
}

How to store a clicked URL as a variable to use in an if statement?

Here is my issue. I want window.open(TargetLink1[0].href); to only be activated if the element alertboxHeader does not exist, TargetLink1 is true and on only the page that was opened when I clicked a link. I have successfully done the first two and the issue is with getting, storing or checking for the right url, I don't know where the issue is. This is my code. The URL clicked would as have to be able to be changed if a new URL is clicked.
var varurl;
var TargetLink1 = $("a:contains('Accept')")
if ((!document.getElementById('alertboxHeader') && (TargetLink1.length) && (window.location.href.indexOf("" + varurl + "") > -1) )) {
window.open(TargetLink1[0].href);
}
function storeurl() {
var varurl = document.URL;
}
document.onclick = storeurl;
I think what you want is something like:
var validSource = (document.referrer !== "") ? (document.location.href.indexOf(document.referrer) == 0) : false;
But be aware that the above compares the document.referrer URL to the current URL as two strings, so that if your referrer were:
http://example.org?q=test
and the current URL (the link they followed) is:
http://example.org/1
it would handle it as not matching because of the query string in the referrer URL.
Here's a better way to handle it, using the URL object prototype (which is not necessarily supported in all browsers, but works in Chrome and FF):
var referrerOrigin = new URL(document.referrer).origin;
var currentOrigin = document.location.origin;
var validSource = ( referrerOrigin == currentOrigin );
The problem is here: document.onclick = storeurl; You should give any id from the document.For Example:
document.getElementById("IdHere").onclick = storeurl;

Get pathname along with PHP vars using JavaScript?

I want to save an entire URL paths to a variable, including the php vars, eg:
mysite.com/pagename?id=2
I can use
var pathname = window.location.pathname;
but this only retrieves the URL without the variables.
Is there a function to retrieve the URL as a literal string?
This should work
window.location.href
Have you tried see if it works:
document.URL
Can you try this,
// Get current page url using JavaScript
var currentPageUrl = "";
if (typeof this.href === "undefined") {
currentPageUrl = document.location.toString().toLowerCase();
}
else {
currentPageUrl = this.href.toString().toLowerCase();
}
Ref: http://www.codeproject.com/Tips/498368/Get-current-page-URL-using-JavaScript
It's hard , this answer explains how to implement it from the top response:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
//var query = getQueryParams(document.location.search);
//alert(query.foo);

How do you get the current sessid from web address and use it in javascript?

Sorry if this is a noob question, network admin unknowingly turned into web developer :) I am trying to understand how to get the current sessid and put it into the javascript where sessid= (current sessid), its on the web address and is generated when you visit the search page. ex: http://www.southerntiredirect.com/shop/catalog/search?sessid=uUQgRHQyekRGJcyWwTFwf5hxep7cdYlV4CdKfunmjxNOQPEgDZdJD2tNgRsD7Prm&shop_param=
<script language="JavaScript">
var url= "http://www.southerntiredirect.com/online/system/ajax_search_manufacturer?sessid=????????";
</script><script type="text/javascript" src="http://www.southerntiredirect.com/online/templatemedia/all_lang/manufacturer.js"></script><input type="hidden" name="sessid" value="sessid??????">
Use my handy-dandy library URLTools!
Library
//URLTools- a tiny js library for accessing parts of the url
function urlAnalyze(url) {
if (url == undefined) {var url = document.location.toString();}
url = url.replace(/\%20/g," ");
//seperates the parts of the url
var parts = url.split("?");
//splits into sperate key=values
if (parts[1] == undefined) {return 1;}
var keyValues = parts[1].split("&");
var key = function () {}
keyValues.forEach(function (keyValue) {
var keyAndValue = keyValue.split("=");
key[keyAndValue[0]] = keyAndValue[1];
});
return key;
}
Then, just call URLAnalyze and get the sessid key.
Usage
var urlKeys = urlAnalyze(),
sessid = urlKeys["sessid"];
here is a great function that grabs whatever you want and returns the key, value for it.
The main portion of this function gets the url using window.location.href and then performs a regular expression on it to find botht he key and the value.
I DO NOT TAKE CREDIT FOR THIS CODE.
Please go the link to see the full example
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(
/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
You could use a simple regexp:
var url = "http://www.southerntiredirect.com/shop/catalog/search?sessid=uUQgRHQyekRGJcyWwTFwf5hxep7cdYlV4CdKfunmjxNOQPEgDZdJD2tNgRsD7Prm&shop_param=";
var match = url.match(/sessid=([^&]+)/);
if (match === null) {
throw new Error("now what? D:");
}
var sessid = match[1];
The regexp in English: look for "sessid=" then capture anything that isn't an &

Detect whether a string isn't a URL in JavaScript?

For example:
You have this string: var x = "/windows/far/away/foo.jpg"
How I now if that string is a URL or no?
What I need to do is:
if (x.charAt(0) == '/') {
x = "http://www.example.com/" + x;
}
else {
x = "http://www.example.com/one/two/three" + x;
}
The problem here is: What will happens when x will be a URL? like:
x = "http://www.externalpage.com/foo.jpg";
As you can see, x.charAt(0) is 'h' and the result will be:
http://www.example.com/one/two/threehttp://www.externalpage.com/foo.jpg
Now, the solution "maybe" like this:
if (is_valid_url( x )) {
....
}
else {
....
}
I'm using this function for this:
function is_valid_url(str) {
var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
'((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
'((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
'(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
'(\?[;&a-z\d%_.~+=-]*)?'+ // query string
'(\#[-a-z\d_]*)?$','i'); // fragment locater
if(!pattern.test(str)) {
alert("Please enter a valid URL.");
return false;
} else {
return true;
}
}
But this function only works with http and https, this will not work with other schemes like ftp or another....
I hope you understand the problem and bring me a solution. Thanks.
To make it work with other protocols, just replace https? in the pattern with an expression that matches any protocols you want, like:
var pattern = new RegExp('^((http|https|ftp|gopher|ssh|telnet):\/\/)?'+ // protocol
It looks like you actually want to normalise an image's URL, i.e. whatever string you are given, you want to convert to an absolute URL. I'd do this:
var x = /* insert arbitrary string here */;
var img = document.createElement('img');
img.src = x;
var absoluteUrl = img.src;
Let the browser do the grunt work.
If this is specific to images, you can also use the img.onload and img.onerror events to detect whether the URL references an image.
Similar to the answer of Lee Kowalkowski, I'd suggest using an <a> element to "make the browser do the work for you". This means that no GET request is fired, protecting you and your users from possible malicious entries during any verify step. It does, however, mean you don't know if the URL points to a real place.
function fixURL(str) {
var a = document.createElement('a');
a.href = str;
return a.href;
}
fixURL('foo/bar'); // "https://stackoverflow.com/questions/16295050/foo/bar"
fixURL('/foo/bar'); // "https://stackoverflow.com/foo/bar"
fixURL('ftp://foo/bar'); // "ftp://foo/bar"
After this step you might also want to check against known "bad" URLs (possibly do that server-side).
Replaced the protocol with ((news|(ht|f)tp(s?)):\/\/) that will match news://, http://, https://, ftp://
function is_valid_url(str) {
var pattern = new RegExp('^((news|(ht|f)tp(s?)):\\/\\/)'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locater
if(!pattern.test(str)) {
alert("Please enter a valid URL.");
return false;
} else {
return true;
}
}

Categories

Resources