conditional use of indexOf function - javascript

I'm using a script that searches a URL for a query string and ignores the query if it is found. The script works, but only when there is a query string present. The error I am getting is Uncaught TypeError: Cannot call method 'indexOf' of undefined so it's obvious where the error is occuring, I'm just not sure how to solve it. I need to only execute indexOf when a query string is found, correct? How can I achieve this?
Here is the JS causing the error:
var href = jQuery(this).attr('href');
var fname = href;
var query = href.indexOf("?");
if (query !== -1) {
fname = href.substr(0, query);
}
I think to fix this I just need to conditionally execute the href.indexOf("?"); portion of the script, but all my attempts thus far have failed.

The test for "?" should work - perhaps your href is empty?
Live Demo
function getFName(link) {
var href = link.href || "no href found";
return href.split("?")[0];
}
var a = document.createElement("a");
a.href = "http://www.google.com/search?q=something";
var fname = getFName(a);
window.console && console.log(fname);
a.href = "http://www.google.com/search";
fname = getFName(a)
window.console && console.log(fname);
Just for your information, there is a search attribute of the link you can test if you must know if there was a querystring
Test the search property instead of href
var query = this.search;
var fname = query?this.href.split("?")[0]:this.href;

Check whether href is undefined before calling indexOf.

http://jsfiddle.net/dqzhz/
var url = getURL("http://www.example.com?q=1&x=2");
alert(url);
function getURL(link) {
url = document.createElement('a');
url.href = link;
return url.protocol + "//" + url.host;
}

http://api.jquery.com/attr/ :
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set.
undefined.indexOf(...) will crash, but you could fall back on an empty string like this :
var query = (href || '').indexOf('?');
It means "something true or an empty string" :
undefined || '' -> ''
"" || '' -> ''
"a" || '' -> "a"

this function returns the value of a querystring or empty string if not found.
function getQueryParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/gi, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS, "i");
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/gi, " "));
}

Related

Regex to get a specific parameter from a URL

assume that we have a URL like this
http://localhost:8080/dev.html?organization=test&location=pr&lang=fr
I'd like to make a regex that takes the organization=test only so that I store it into a var.
So in case I have http://localhost:8080/dev.html?organization=test, I get the organization=test.
http://localhost:8080/dev.html?lang=fr&organization=test, I get organization=test.
No matter how the URL is formed or the order of the parameters, I get
organization=<organization>
Thank you
Why use RegEx or split ? Try this:
function getOrganization(){
return new URLSearchParams(location.search).get('organization')
}
(requires a polyfill for the URL API in IE)
You can use this function, assuming the parameter name does not even if the parameter does contain any characters considered special within RegExp:
function getParam(url, name, defaultValue) {
var a = document.createElement('a');
a.href = '?' + unescape(String(name));
var un = a.search.slice(1);
var esc = un.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&');
var re = new RegExp('^\\?&*(?:[^=]*=[^&]*&+)*?(' + esc + ')=([^&]*)');
a.href = url;
var query = a.search;
return re.test(query) ? query.match(re).slice(1).map(decodeURIComponent) : [un, defaultValue];
}
var url = 'http://localhost:8080/dev.html?lang=fr&organization=test&crazy^ ()*key=cool';
console.log(getParam(url, 'organization'));
console.log(getParam(url, 'lang'));
console.log(getParam(url, 'crazy^ ()*key'));
console.log(getParam(url, escape('crazy^ ()*key')));
console.log(getParam(url, encodeURIComponent('crazy^ ()*key')));
console.log(getParam(url, 'foo', 'bar'));
RegExp escape method borrowed from How to escape regular expression in javascript?
Usage
getParam(url, name[, defaultValue])
url - A well-formed URL
name - The parameter name to search
defaultValue (optional) - If not found, what value to default to. If not specified, defaultValue is undefined
return - [ unescape(name), found ? stringValue : defaultValue ]
Why use regex? Try this.
function getOrganization(){
var params = location.search.split('?')[1].split('&');
for(var i = 0; i < params.length; i++){
if(params[i].split('=')[0] == 'organization') return params[i].split('=')[1];
}
}

How to access REAL querystring param in javascript with URL rewrite in place

I am trying to alert the querystring param in jquery because i need that ID on a page load so that i can create some html elements when the control is loaded. I cant seem to access the parameter as the URL rewrite in place and URL looks diff then the original one.
Original URL
www.somesite.com/camping?ProductId=2457&ism=0&cl=PURPLE
URL seen in browser
www.somesite.com/camping/travel-mug-16oz-double-wat-with-adapter-p2457.aspx?ism=0&cl=PURPLE
now, how do i access the ProductId querystring value in Jquery.
Jquery
$(document).ready(function () {
var param = getParameterByName("ProductId");
alert(param) // shows PURPLE as cl in URL is set to cl=PURPLE
});
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
EDIT:
here is the screenshot when i am trying to access the Querysting object on serverside..
Your current code is attempting to access the value from the querystring, which no longer exists as it has been rewritten on the server.
You can use a regular expression to dissect the rewritten URL, no jQuery required. Assuming your productId is always prefaced by -p and is immediately followed by .aspx, then this will work:
var url = 'www.somesite.com/camping/travel-mug-16oz-double-wat-with-adapter-p2457.aspx?ism=0&cl=PURPLE'
var matches = url.match(/-p(\d+)\.aspx/);
var productId = matches && matches[1];
console.log(productId); // = 2457
productId will be null if there are no matches to the regex.
Example fiddle

Cannout set selected item jquery

I'm taking values from the url using the following function.
function getParameterByName( name ) //courtesy Artem
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
The url is as following.
http://localhost:9157/layout?oc=ARES&sn=Charitha&on=Araliya%20Restaurant.
This is the code where I try to set the element to be selected.
var oc = getParameterByName('oc');
$("#" + oc).prop("selected", true);
No matter how I checked using firebug and other debugging tools, the element doesn't get selected! is there anything that I'm doing wrong here! I checked whether the value from the getParameterByName() method returns correct. The values are correct! bt it doesn't work.
Try this:-
$("#my-Select option[text=" + oc +"]").attr("selected","selected") ;

How do I extract "search term" from URLs?

How do I extract "test" from the following URL?
http://www.example.com/index.php?q=test&=Go
I've found the a script to extract the path (window.location.pathname), but I can't find or figure out how to extract or split the URL.
-ben
var m = window.location.search.match(/q=([^&]*)/);
if (m) {
alert(m[1]); // => alerts "test"
}
var myURL = 'http://www.example.com/index.php?q=test&=Go';
function gup( name ) //stands for get url param
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( myURL );
if( results == null )
return "";
else
return results[1];
}
var my_param = gup( 'q' );
Here is the jsfiddle
Or you can use jQuery's plugin:
URL Parser JQuery
If you just want the value of the first term, then:
function getFirstSeachValue() {
var s = window.location.search.split('&');
return s[0].split('=')[1];
}
If you want the value of the 'q' term, regardless of where it is in the search string, then the following returns the value of the passed term or null if the term isn't in the search string:
function getSearchValue(value) {
var a = window.location.search.replace(/^\?/,'').split('&');
var re = new RegExp('^' + value + '=');
var i = a.length;
while (i--) {
if (re.test(a[i])) return a[i].split('=')[1];
}
return null;
}
Both are just examples of course and should test results along the way to prevent unexpected errors.
--
Rob

How can I get URL parameter in a jquery ready function?

I have the following:
$(document).ready(function() {
window.location.href='http://target.SchoolID/set?text=';
});
So if someone comes to a page with the above mentioned code using a url like:
Somepage.php?id=abc123
I want the text variable in the ready function to read: abc123
Any ideas?
you don't need jQuery. you can do this with plain JS
function getParameterByName( name ) //courtesy Artem
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
and then you can just get the querystring value like this:
alert(getParameterByName('text'));
also look here for other ways and plugins: How can I get query string values in JavaScript?
check out the answer to this questions:
How can I get query string values in JavaScript?
that'll give you the value of the id parameter from the query string.
then you can just do something like:
$(document).ready(function() {
var theId = getParameterByName( id)
var newPath = 'http://target.SchoolID/set?text=' + theId
window.location.href=newPath;
});
To help people coming after me that want to have multiple variables and to enhance Moin's answer here is the code for multiple variables:
function getParameterByName( name ) //courtesy Artem
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
{
if ((results[1].indexOf('?'))>0)
return decodeURIComponent(results[1].substring(0,results[1].indexOf('?')).replace(/\+/g, " "));
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
}

Categories

Resources