jQuery.grep() match URL both www and non www, http/https - javascript

I am using jquery to search a json string for the matched url and then fetch all the data inside that object.
I fetch the url with
var url = window.location.href;
However this returns
http://somesite.com/
inside the json string could be any of the following
http://somesite.com/
http://somesite.com
http://www.somesite.com/
http://www.somesite.com https://somesite.com/
etc etc.
My code is to match the url and then do something. How would I go about using jQuery.grep() to take the different style urls in the query? Below is my code so far.
var url = window.location.href;
var json = exampleJsonString;
var js = JSON.parse(json);
var result = $.grep(js, function(e){ return e.url == url; });
if (result.length == 0) {
// not found :(
console.log('Not found');
} else if (result.length == 1) {
// Result matched
console.log(result);
}
else {
// multiple items found
console.log('multiple items found');
console.log(result);
}
What I want to do is check for somesite.com using jquery grep. As in this line it checks if the string is equal.
var result = $.grep(js, function(e){ return e.url == url; });

You can use grep function to filter the records. Here in your case want to check different URL's in the object like 'http://somesite.com/','http://somesite.com' etc, mention all the URL's that you want to consider in grep function. Here is the sample code.
var varObj = jQuery.grep(dataobject, function (a) {
if (a.url == "http://somesite.com/" || a.url == "http://somesite.com" || a.url == "http://www.somesite.com/")
return true;
});

Related

Set body class based on url with params

Im trying to set a body class based on the url - I can get it to work with a plain /Tablet/ url, like the code below.
But I need to set it to a url that has params in it, and I can't get that to work. How do I do it with this url?
/Tablets/?param=grid&pld0page=1&spcs=1
Script:
$(function() {
var loc = window.location.href; // returns the full URL
if(/Tablets/.test(loc)) {
$('body').addClass('test');
}
});
If, as you have mentioned in comments, the query parameter order is important, you can use this...
var url = location.pathname + location.search
console.info(url)
$(document.body).toggleClass('test',
url === '/Tablets/?param=grid&pld0page=1&spcs=1')
This lets you omit the URL scheme, host and port parts, focusing only on the path and query parameters.
You just have to search for text you want in the url string. You are doing fine in the code above. Just change
$(function() {
var loc = window.location.href; // returns the full URL
if(loc.includes('Tablets')) { // will return true/false
$('body').addClass('test');
}
});
Read on includes or here. You can do the same for other tests too, if you are checking for other strings in url. Hope this helps.
You can use this
$(function() {
var url = window.location.href;
url = url.replace(/^.*\/\/[^\/]+/, '')
if(url == '/Tablets?param=grid&pld0page=1&spcs=1') {
$('body').addClass('test');
}
});
If your URL is "http://www.google.com/?param=grid&pld0page=1&spcs=1", then the above queryString variable would be equal to "?param=grid&pld0page=1&spcs=1".
You can check the string is not empty
Replace your code with this
var loc = window.location.href; // returns the full URL
var url = loc.split( '/' );
var chunk = url[ url.length - 2 ];
if(loc.indexOf(chunk) >= 0) {
$('body').addClass('test');
}
var loc = 'http://localhost/Tablets/?param=grid&pld0page=1&spcs=35';
var patt = new RegExp("/Tablets/");
if(patt.test(loc) && loc.split('?').length > 1)
{
console.log('true');
$('body').addClass('test');
}
else
{
console.log('false');
$('body').removeClass('test');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

URL validate with regular expression and add "http://" when it's missing

I am trying to make a function to validate url regular expression,
and add "http://" if it's missing at the same time.
I am quite new to Javascript and coding, and most part of the below code
is what I have followed a Youtube tutorial.
But I wanted to add a function to prepend "http://" when it's missing,
since with the current regex, both "www.google.com" and "http://www.google.com"
is valid. The problem with this is when I actually click to visit the website,
the ones saved without "http://" at start, doesn't go to the site.
function validateForm(siteName, siteUrl) {
if(!siteName || !siteUrl) {
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var result = siteUrl.search(new RegExp(/^http:\/\//i));
if(!siteUrl.match(regex)) {
alert('Please use a valid URL');
return false;
}
else if(siteUrl.match(regex) && !result) {
siteUrl = "http://" + siteUrl
return true;
}
else {
return true;
}
}
You can use the .indexOf() string method to determine if http:// is at the beginning of the string. However, you may run into problems prepending http:// if the URL requires https://.
else if(siteUrl.match(regex) && !result) {
// Check to see if the string starts with "http://"
// indexOf() returns the index position of the supplied
// string argument within the string.
if(siteUrl.indexOf("http://") !== 0){
siteUrl = "http://" + siteUrl
}
return true;
}
Also (as #m_callens points out in the comments below), your siteUrl variable is a function argument, so you won't be able to access it from outside of the function. Instead you should not pass it into the function at all and just have it declared in a higher scope:
var siteUrl = // Code that initializes the variable
function validateForm(siteName) {
if(!siteName || !siteUrl) {
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var result = siteUrl.search(new RegExp(/^http:\/\//i));
if(!siteUrl.match(regex)) {
alert('Please use a valid URL');
return false;
}
else if(siteUrl.match(regex) && !result) {
// Check to see if the string starts with "http://"
// indexOf() returns the index position of the supplied
// string argument within the string.
if(siteUrl.indexOf("http://") !== 0){
siteUrl = "http://" + siteUrl
}
}
else {
return true;
}
}

Javascript/jQuery search json for a string then run a function

I need to run a function matchFound() if a string is found in an external json file.
This is what I have so far:
function init(){
$.ajax({
type: "GET",
url: "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=50&callback=?&q=http://www.domain.com/feed.rss",
dataType: "json",
success: parseData
});
}
function parseData(data){
var string_to_find = "Hello World!";
// look into the data and match the string
}
function matchFound(str, string_to_find){
alert('Match found in string - '+ str +'\r\n While looking for the string- '+ string_to_find);
return true;
}
function matchNotFound(){
alert('No Match found!');
}
But I don't know how to parse the Json data and search for a string.
I have this for XML (thanks #Ohgodwhy) but not sure how to translate for json
function parseXml(xml){
var string_to_find = "Hello World!";
$(xml).find('title').each(function(){
var str = $(this).text();
if(str.indexOf(string_to_find) > -1){
if(matchFound(str, string_to_find)){
return false;
}
}
});
}
The search location within the variables is: responceData > feed > entries > [0] or 1 or [2] etc > contentSnippet
I only need to match the first 10 characters.
If a match is found then run the funciton matchFound() or if not found run the function matchNotFound()
Any help with this is very much appreciated.
C
you have to iterate json recursively and then search for the string
function parseData(data){
var string_to_find = "Hello World!";
var is_found = iterate(data , string_to_find);
if(is_found === true){
matchFound(JSON.stringify(data), string_to_find);
}else{
matchNotFound(string_to_find);
}
// look into the data and match the string
}
function iterate(obj , string_to_find) {
for(var key in obj) { // iterate, `key` is the property key
var elem = obj[key]; // `obj[key]` is the value
console.log(elem, string_to_find);
if(typeof(elem)=="string" && elem.indexOf(string_to_find)!==-1) {
return true;
}
if(typeof elem === "object") { // is an object (plain object or array),
// so contains children
return iterate(elem , string_to_find); // call recursively
}
}
}

Getting URL data with JavaScript (split it like php $_GET)

I found this script at Stack Overflow:
window.params = function(){
var params = {};
var param_array = window.location.href.split('?')[1].split('&');
for(var i in param_array){
x = param_array[i].split('=');
params[x[0]] = x[1];
}
return params;
}();
This splits a URL into data, like PHP does with $_GET.
I have another function, which uses it and it refreshes the iframe. I want to get the data from the URL and add another with it if some of these data exist. Firebug shows me, that search is not defined, but why?
function RefreshIFrames(MyParameter) {
var cat = window.params.cat;
var category = window.params.category;
var search = window.params.search;
if (search.length>0 && category.length>0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search="+search+"&category="+category+"&rendez="+MyParameter;
}
if (cat.length>0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat="+cat+"&rendez="+MyParameter;
}
if (cat.length==0 && category.length==0 && search.length==0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez="+MyParameter;
}
alert(window.location);
}
If you want to add rendez OR change the existing rendez, do this - I am assuming the URL is actually beginning with http://siriusradio.hu/kiskunfelegyhaza/video/index.php so no need to create it. Let me know if you need a different URL than the one you come in with
The parameter snippet did not work proper (for in should not be used on a normal array)
Here is tested code
DEMO
DEMO WITH DROPDOWN
function getParams(passedloc){
var params = {}, loc = passedloc || document.URL;
loc = loc.split('?')[1];
if (loc) {
var param_array = loc.split('&');
for(var x,i=0,n=param_array.length;i<n; i++) {
x = param_array[i].split('=');
params[x[0]] = x[1];
}
}
return params;
};
function RefreshIFrames(MyParameter,passedloc) { // if second parm is specified it will take that
var loc = passedloc || document.URL; //
window.param = getParams(loc);
loc = loc.split("?")[0]+"?"; // will work with our without the ? in the URL
for (var parm in window.param) {
if (parm != "rendez") loc += parm +"="+ window.param[parm]+"&";
}
// here we have a URL without rendez but with all other parameters if there
// the URL will have a trailing ? or & depending on existence of parameters
loc += "rendez="+MyParameter;
window.console && console.log(loc)
// the next statement will change the URL
// change window.location to window.frames[0].location to change an iFrame
window.location = loc;
}
// the second parameter is only if you want to change the URL of the page you are in
RefreshIFrames("rendez1","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat=cat1&search=search1");
RefreshIFrames("rendez2","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search=search2");
RefreshIFrames("rendez3","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez=xxx&search=search2");
RefreshIFrames("rendez4","http://siriusradio.hu/kiskunfelegyhaza/video/index.php");
// here is how I expect you want to call it
RefreshIFrames("rendez5"​); // will add or change rendez=... in the url of the current page

How to add a param to a URL that trigger jQuery to run a function on load

Is there a way to add a url param like: http://site.com?open=true
And on document ready, if jQuery sees the open param set to true execute a function?
Thanks
first lets make a good Query string searcher in JS
function querySt(qsName, url)
{
var theUrl;
if (url == null || url == undefined)
theUrl = window.location.search.substring(1); else theUrl = url;
var g = theUrl.split("&");
for (var i = 0; i < g.length; i++) {
var pair = g[i].split("=");
if (pair[0].toLowerCase() == qsName.toLowerCase())
{
return pair[1];
}
}
return null;
}
$(function (){
if (querySt("open")!='true') return;
});
taken from website http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
function $_GET(q,s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
You can test location.href with a regex:
if (location.href.match(/open=true/)
// do something
You might want to work on the regex though, to make sure it works for you.

Categories

Resources