How to match specific URL in JavaScript or jQuery? - javascript

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
}
}

Related

Current page URl check by 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>

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;

Send multiple parameter in ajax request using javascript

So I want to use ajax request and I know how to use it.
But problem that i had that I want to pass parameters to request. So My first page had 4 parameter then I build url like this,
var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;
but now parameter is increasing like now I have 20 more. So now building url like this going to be messy approach. Is there a better way to do this.
Here is my function where i am building URL in javascript function.
function closeAssessment() {
var closeReason = document.getElementById("SectionClousureReason");
var closeReasonStr = closeReason.options[closeReason.selectedIndex].value;
var closeCmt=document.getElementById("SectionCloseAssessmentCmt").value;
var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;
ajaxRequest(url);
return;
}
edit:
As you ask here is my ajaxRequest function,
function ajaxRequest(url) {
strURL = url;
var xmlHttpRequest = false;
var self = this;
// Mozilla, Safari
if (window.XMLHttpRequest) {
self.xmlHttpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
self.xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpRequest.open("POST", strURL, true);
self.xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
self.xmlHttpRequest.onreadystatechange = function() {
if (self.xmlHttpRequest.readyState == 4) {
if (self.xmlHttpRequest.status == 200) {
var htmlString = self.xmlHttpRequest.responseText;
var parser = new DOMParser();
var responseDoc = parser.parseFromString(htmlString, "text/html");
window.close();
} else {
ajaxFailedCount++;
// Try for 1 min (temp fix for racing condition)
if (ajaxFailedCount < 1200) {window.setTimeout(function() {ajaxRequest(url)}, 50);}
else {alert("Refresh failed!")};
}
}
}
self.xmlHttpRequest.send(null);
}
You could make an object with the key/value pairs being what you want added to the URL.
var closeReason = document.getElementById("SectionClousureReason");
var params = {
PAGE_ID: 'BPCLA',
ACTION: 'closeAssessment',
SAVE_FLAG: 'true',
closeReasonStr: closeReason.options[closeReason.selectedIndex].value,
closeCmt: document.getElementById("SectionCloseAssessmentCmt").value
};
Then add them to the URL via a loop.
var url = "./ControllerServlet?";
var urlParams = Object.keys(params).map(function(key){
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
url += urlParams;
ajaxRequest(url);
Note: I added encodeURIComponent just to be safe.
EDIT: From your comment, it seems you want to submit a <form> but you want to use AJAX to do so. In that case, you can loop over the form elements and build the above params object.
var params = {
PAGE_ID: 'BPCLA',
ACTION: 'closeAssessment',
SAVE_FLAG: 'true'
};
var form = document.getElementById('yourForm'),
elem = form.elements;
for(var i = 0, len = elem.length; i < len; i++){
var x = elem[i];
params[x.name] = x.value;
}
Build up an object of your parameters and put them in the uri through a loop like this:
var values= {
page_id: 'BPCLA',
action: 'test'
},
uri_params = [],
uri = 'http://yoururl.com/file.php?';
for (var param in values) uri_params.push( encodeURIComponent( param ) + '=' + encodeURIComponent( values[ param ] ) );
uri = uri + uri_params.join( '&' );
console.log( uri );
Or consider using POST to transport your parameters, as many browsers have limitations on the query string.
Edit: you can also build yourself a function which traverses your form and builds up the values object for you so you don't have to do it manually.
Be aware however that anyone can inject custom url paramters simpy by appending form elements before submitting the form (by using the developer tools for example) so keep that in mind.
If you are using jQuery you can use .serializeArray() or have a look at this answer for a possible function you could use.

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 &

Categories

Resources