How to get the parameter value from URL in Jquery? - javascript

Hi all i have an url where i need to get an parameter from the url
var URL="http://localhost:17775/Students/199/Kishore"
//here from the url i need to get the value 199
this is what i had been trying but the value is null here
function getURLParameter(name) {
return parent.decodeURI((parent.RegExp(name + /([^\/]+)(?=\.\w+$)/).exec(parent.location.href) || [, null])[1]);
};
$(document).ready(function() {
getURLParameter("Students");
//i need to get the value 199 from the url
});

jQuery is not needed for this, though it could be used. There are lots of ways to skin this cat. Something like this should get you started in the right direction:
var URL="http://localhost:17775/Students/199/Kishore";
var splitURL = URL.split("/");
var studentValue = "";
for(var i = 0; i < splitURL.length; i++) {
if(splitURL[i] == "Students") {
studentValue = splitURL[i + 1];
break;
}
}
Here's a working fiddle.
Edit
Based on the comments, indicating that the position will always be the same, the extraction is as simple as:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.split("/")[4];

This is what you're looking for since the URL parameter will keep changing:
http://jsbin.com/iliyut/2/
var URL="http://localhost:17775/Students/199/Kishore"
var number = getNumber('Students'); //199
var URL="http://localhost:17775/Teachers/234/Kumar"
var number = getNumber('Teachers'); //234
function getNumber(section) {
var re = new RegExp(section + "\/(.*)\/","gi");
var match = re.exec(URL);
return match[1];
}

I would do the following:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.match('/Students/(\\d+)/')[1]; //199

Related

I need to get values from a url after (#) with jquery

I have this url:
http://test.words.aspx#word_id=1034374#lang_code=en
I need to get the values of word_id and Language code and assign them to variables.
var word_id = 1034374;
var lang_kod = en;
Here is the code you need:
var link = window.location;
var data = link.split("#");
var word_id = data[1].split("=")[1];
var lang_code = data[2].split("=")[1];
With window.location you get the url that you currently are (an alternative is document.location.
Then you split it by the hash symbol (link.split("#")) and the result is stored as an array of strings (data) which now contains http://test.words.aspx at index 0, word_id=1034374 at index 1 and lang_code=en at index 2;
What you have to do now is split the string at index 1 by the equals symbol (data[1].split("=")). This also is an array of string which has the word_id at index 0 and 1034374 at index 1 which is what you need (data[1].split("=")[1]).
Following the same logic you also get the lang_code variable.
Test it here:
var link = "http://test.words.aspx#word_id=1034374#lang_code=en"
var data = link.split("#");
var word_id = data[1].split("=")[1];
var lang_code = data[2].split("=")[1];
console.log("Word ID = " + word_id);
console.log("Lang Code = " + lang_code);
Hope this was helpful :)
You should really only have one URL fragment. But in your case you could do the following to achieve this.
var url = "http://test.words.aspx#word_id=1034374#lang_code=en"; // or use window.location;
var url_splitted = url.split('#');
alert((url_splitted[1]).split('=')[1]); // showing you the values
alert((url_splitted[2]).split('=')[1]); // showing you the values
var work_id = (url_splitted[1]).split('=')[1];
var lang_code = (url_splitted[2]).split('=')[1];
Working JSFiddle: https://jsfiddle.net/o0nwyvfz/
Note:
If you are about to use multiple URL fragments, I'd suggest you to use URL parameters e.g.: http://test.words.aspx?word_id=1034374&lang_code=en
Which you could retrieve by:
A solution provided by: http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
And this is how you can use this function assuming the URL is,
http://test.words.aspx?word_id=1034374&lang_code=en
var tech = getUrlParameter('word_id');
var blog = getUrlParameter('lang_code');

How to get multiple named querystring values in jQuery/Javascript?

I've got the following parameters
/Search?category=1&attributes=169&attributes=172&attributes=174&search=all
I'm trying to get just the attributes querystring values as an array in javascript, for example.
attributes = ['169','172','174']
Bearing in mind there may be other parameters that are irrelevant such as search or category.
Might not the proper answer but just tried
var str = "/Search?category=1&attributes=169&attributes=172&attributes=174&search=all";
var str1 = str.split("&");
var attributesArray = [];
for(var i=0; i<str1.length; i++) {
if (str1[i].includes("attributes")) {
attributesArray.push(str1[i].replace("attributes=", ""));
}
}
Fiddle https://jsfiddle.net/5Lkk0gnz/
You can do it like this:
(function() {
function getJsonFromUrl(url) {
var query = url.substr(1);
var arr = [];
query.split("&").forEach(function(part) {
var item = part.split("=");
arr.push(decodeURIComponent(item[1]));
});
return arr;
}
var url = "https://example.com?category=1&attributes=169&attributes=172&attributes=174&search=all";
var params = getJsonFromUrl(url);
console.log(params);
})();
Hope this helps!
This should do what you want, assuming you already have your url:
var url = "/Search?ategory=1&attributes=169&attributes=172&attributes=174&search=all";
var attrs = url
.match(/attributes=\d*/g)
.map(function(attr){
return Number(attr.replace("attributes=", ""));
});
console.log(attrs); //=> [169, 172, 174]

Accessing Stored Object

I have an object "Driver" defined at the beginning of my script as such:
function Driver(draw, name) {
this.draw = draw;
this.name = name;
}
I'm using this bit of JQuery to create new drivers:
var main = function () {
// add driver to table
$('#button').click(function ( ) {
var name = $('input[name=name]').val();
var draw = $('input[name=draw]').val();
var draw2 = "#"+draw;
var name2 = "driver"+draw
console.log(draw2);
console.log(name2);
if($(name2).text().length > 0){
alert("That number has already been selected");}
else{$(name2).text(name);
var name2 = new Driver(draw, name);}
});
That part is working great. However, when I try later on to access those drivers, the console returns that it is undefined:
$('.print').click(function ( ) {
for(var i=1; i<60; i++){
var driverList = "driver"+i;
if($(driverList.draw>0)){
console.log(driverList);
console.log(driverList.name);
}
If you're interested, I've uploaded the entire project I'm working on to this site:
http://precisioncomputerservices.com/slideways/index.html
Basically, the bottom bit of code is just to try to see if I'm accessing the drivers in the correct manner (which, I'm obviously not). Once I know how to access them, I'm going to save them to a file to be used on a different page.
Also a problem is the If Statement in the last bit of code. I'm trying to get it to print only drivers that have actually been inputed into the form. I have a space for 60 drivers, but not all of them will be used, and the ones that are used won't be consecutive.
Thanks for helping out the new guy.
You can't use a variable to refer to a variable as you have done.
In your case one option is to use an key/value based object like
var drivers = {};
var main = function () {
// add driver to table
$('#button').click(function () {
var name = $('input[name=name]').val();
var draw = $('input[name=draw]').val();
var draw2 = "#" + draw;
var name2 = "driver" + draw
console.log(draw2);
console.log(name2);
if ($(name2).text().length > 0) {
alert("That number has already been selected");
} else {
$(name2).text(name);
drivers[name2] = new Driver(draw, name);
}
});
$('.print').click(function () {
for (var i = 1; i < 60; i++) {
var name2 = "driver" + i;
var driver = drivers[name2];
if (driver.draw > 0) {
console.log(driver);
console.log(driver.name);
}

Javascript Regex first character after occurence

I have a pager with this url: news?page=1&f[0]=domain_access%3A3".
I need a regex to replace the page=1 with page=2
The 1 and 2 are variable, so I need to find page= + the first character after that.
How can I do that
#EDIT:
from the answers, I distilled
var url = $('ul.pager .pager-next a').attr("href");
var re = /page=(\d+)/i;
var page = url.match(re);
var splitPage = page[0].split("=");
var pageNumber = parseInt(splitPage[1]);
pageNumber += 1;
var nextPagePart = 'page=' + pageNumber;
var nextPageUrl = url.replace(re, nextPagePart);
$('ul.pager .pager-next a').attr("href", nextPageUrl);
There might be a shorter approach ?
Like this:
var url = 'news?page=1&f[0]=domain_access%3A3"';
var page = 2;
url = url.replace(/page=\d+/, 'page=' + page);
EDIT
To achieve what did in your edit:
var obj = $('ul.pager .pager-next a');
var url = obj.attr('href');
url = url.replace(/page=\d+/, 'page=' + (++url.match(/page=(\d+)/)[1]));
obj.attr('href', url);
If you want to replace only a page number and leave the rest You can try something like this:
s/\(.*\)page=\d{1,}\(.*\)/\1number_to_replace\2/

Find id number in url using javascript

Currently I am scraping the end of an url using javascript like so:
var url = document.URL;
var sale = url.substring(url.lastIndexOf('/') + 1);
if(sale != "")
So if there is this /sales/1234 it would pick it up, trouble is it still works for something else like sales/anotherword/1234, is there an easy way to adjust this to only pick up the number after "/sales/"?
You could try using regular expressions:
var url = document.URL;
var sale = null;
var matches = url.match(/\/sales\/(\d+)/);
if(matches.length && matches[1]){
sale = matches[1];
}
You could do a bit more validating:
Make sure there is no / after the one after sales.
Make sure that the value you get is a number.
Something like this could work:
var url = document.URL;
var sale = url.substring(url.lastIndexOf('/sales/') + 1);
if(sale.indexOf('/') < 0 && !isNaN(sale)) {
//Handle the sale
}
else {
//sale either contains a / or is not a number
}
You could also do this :
var sale = parseInt(url.split('/sales/')[1], 10);
if (!isNaN(sale)) {
// do something
}
parseInt() returns NaN (Not A Number) in case of failure.
Here is a function :
function toSaleId(url) {
var id = parseInt(url.split('/sales/')[1], 10);
if (!isNaN(id)) return id;
}
Usage examples :
var sale = toSaleId('/sale/1234'); // 1234
var sale = toSaleId('/sale/1234/anotherworld'); // 1234
var sale = toSaleId('/sale/anotherworld/1234'); // undefined

Categories

Resources