JS - read value of submitted form [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get query string values in JavaScript
If one submits a GET form, the resulting address will look like www.example.com/stuff?param1=stuff&param2=morestuff. I know how to read/set the value of a form field on a page, but how do I read submissions from the previous page (in the URL) with JavaScript? I guess I could take the url and split() it, to get the parameters, but is there any quicker/simpler way to read param1 (just an example)?
Note: this is not a duplicate of this, since that question is about how to do it in PHP.

function getQuerystring(key)
{
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,\\\]);
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs != null)
return(qs[1]);
else
return("");
}

No, there's no simple way to do that.
Use something like this:
var qstring = {}, src = location.search.substring(1).split("&");
for (var i = 0; i < src.length; i++) {
var parts = src[i].split("=");
qstring[unescape(parts[0])] = unescape(parts.slice(1).join("="));
}
Now the object qstring is a key/value map of the query string. Keep in mind that values with the same key are overwritten, so you may want to store them in an indexed array instead of an associative array.

I think this topic is answer to your question.
function gup( name )
{
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 results[1];
}
You can try also this one

jQuery URL Parser Plugin. In case you want to use jQuery.
jsUri. In case jQuery is too heavy for you.

Related

How to parse url to get desired value [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 6 years ago.
How can I parse a link in jqueryjavascript?
I have the url (some path)/restaurantProfile.php?id=51
And I want to parse this to only obtain the 51. (keep in mind this needs to be generalized. The id won't obviously be always 51...)
Thanks in advance!
You can split the string at id=:
var url = 'some/path/restaurantProfile.php?id=51';
var id = url.split('id=')[1]; // 51
I forget where I saw this, but here is a nice jquery function you can use for this:
//jQuery extension below allows for easy query-param lookup
(function($) {
$.QueryString = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=', 2);
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'))
})(jQuery);
Usage like so:
var restaurantId = $.QueryString["id"];
You can make use of Regular Expression in javascript. RegExp Object provides methods to Match the Regular Expression with a input String.
You can make use of string object split method to split the string by using a separator character.
There is a similar question at How can I get query string values in JavaScript? for more options.
You can use the URLSearchParams API to work with the query string of a URL
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
// get the current url from the browser
var x = new URLSearchParams(window.location.search);
// get the id query param
var id = x.get('id');

Extracting a URL parameter with JavaScript [duplicate]

This question already has answers here:
Get escaped URL parameter
(19 answers)
Closed 8 years ago.
I have a URL:
http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382
Edit: I should also not the url is stored in a variable and I want it to work something like this:
$(".videothumb a").live('click', function() {
var URL = < do something to cut the string >
console.log(URL);
return false;
});
And I want to cut the URL starting from "=" and ending at "&" so I'll end up with a string like this: "JssO4oLBm2s".
I only know of the slice() function but I believe that only takes a number as beginning and end points.
Using .split() will give a position based solution which will fail the order of parameters changes. Instead I think what you are looking for is the value of parameter called v for that you can use a simple regex like
'http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382'.match('[?&]v=(.*?)(&|$)')[1]
Try
'http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382'
.split('=')[1] // 'JssO4oLBm2s&list'
.split('&')[0] // 'JssO4oLBm2s'
Or, if you want to be sure to get the v parameter,
var v, args = 'http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382'.split("?")[1].split('&');
for(var i = args.length-1; i>=0; --i) {
var data = args[i].split('=');
if(data[0]==='v') { v = data[1]; break; }
}
Use .split(). Separated to 2 lines for clarity
var first = "http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382".split('=')[1]
var result = first.split('&')[0]; //result - JssO4oLBm2s
v = 'JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382';
var vamploc = v.indexOf("&");
vstring = v.substr(0, vamploc);
You can play with the code a bit to refine it, but the general concepts work.
use Regexp (?:v=)(.+?)(?:&|$)
Fiddle DEMO
"http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382".match('(?:v=)(.+?)(?:&|$)')[1]
Reference
http://gskinner.com/RegExr/

Getting a number from within a URL [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I get query string values?
I am trying to get a page number from a URL during a test. The URL looks like this:
http://www.site.com/objects/search/8765XX/results?page=2&sort_att=posted_dt&sort_dir=desc
What I want to get is the page number right after 'page=' in the url.
In one line, by splitting url. jsfiddle
var url = "http://www.site.com/objects/search/8765XX/results?page=2&sort_att=posted_dt&sort_dir=desc";
var pageNumber = parseInt(url.split("page=")[1].split("&")[0], 10);
A simple pure JavaScript implementation I can think of would be something like the following:
var url = http://www.site.com/objects/search/8765XX/results?page=2&sort_att=posted_dt&sort_dir=desc
var matchedPos = url.search("page=\\d");
var matched = url.substr(matchedPos);
var num = matched.split("=")[1]; //might need to parse
I have this small function to fetch URL parameters (I found it on internet many years ago) :
function getUrlParameter(name, defaultValue) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ) return defaultValue;
else return results[1];
}
I use it like this :
pageNumber = parseInt(getUrlParameter('page'), 10);

Get a parameter from a rewritten URL with javascript

I am trying to get a url parameter using javascript so i can pass the paramter to google maps
The problem is i'm using mod rewrite on the url
www.mysite.com/1/my-event
instead of
www.mysite.com/mypage.php?id=1&name=my-event
I've tried doing an alert but it comes up blank
Here is the javascript function that will work if i don't rewrite the url
function gup( name ){
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 results[1];
}
The rewritten format, with the query-string, isn't available to your JavaScript.
You'll have to grab the value out of location.pathname (/1/my-event in your example), instead:
var params = window.location.pathname.split('/').slice(1); // ["1", "my-event"]
var id = params[0];
var name = params[1];
Just split the URL on / characters and take the last elements in the resulting array, mapping them to the names you expect.

Is this JavaScript code safe?

I have found the following JS on the web.
It is a function to get url params values.
function get_url_param(param) {
param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+param+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec(window.location.href);
if( results == null )
return '';
else
return results[1];
}
However always when I see a exec() function I think: Eeek!
So my question is: is it safe?
Side bet: If you think this function sucks and have a better option don't hesitate to share :)
The above function uses the real url but I only need to parse a string which contains an URL.
The .exec() you see in your function is not of the window but of the RegExp object.
So it is perfectly fine to use.
I wouldn't confuse a Regexp exec with an eval. A little clunky but it should work.
Regexp#exec is safe, albeit not a very nice interface.
Side bet: If you think this function sucks and have a better option don't hesitate to share :)
yeeep :-)
param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
This doesn't use a global regexp so you are only replacing one instance of each bracket; field[][] wouldn't work. Also you don't need the character group... param.replace(/\[/g, '\\[') would have worked. Or, the non-regexp replacement idiom, param.split('[').join('\\[').
Then:
var regexS = "[\\?&]"+param+"=([^&#]*)";
you're not escaping nearly enough characters to be able to drop them into a regexp and have them mean their literal selves. See this question for a more watertight alternative.
Anyway this kind of regex hacking still isn't a good way of parsing URLs/query strings. This doesn't deal properly with ; or %-encoding, or + for space, and it may trip on parameter lookalikes elsewhere in the URL.
Instead, let's first get the query string on its own. If you have a link or location object, you can get it from the the .search property . If you only have a string URL, you can turn it into a link object to get this reliably:
function getQueryString(url) {
var a= document.createElement('a');
a.href= url;
return a.search;
}
Now you can parse it into by dropping the leading ?, splitting on & or ;, then dropping the URL-decoded results into a JS Object:
function parseQuery(query) {
var lookup= {};
var params= query.slice(1).split(/[&;]/);
for (var i= 0; i<params.length; i++) {
var ix= params[i].indexOf('=');
if (ix!==-1) {
var name= decodeURIComponent(params[i].slice(0, ix));
var value= decodeURIComponent(params[i].slice(ix+1));
if (!(name in lookup))
lookup[name]= [];
lookup[name].push(value);
}
}
return lookup;
}
This makes it easy to look up parameters:
var url= 'http://www.example.com/?a=b&c=d&c=%65;f[]=g#h=i';
var pars= parseQuery(getQueryString(url));
alert(pars.a); // ['b']
alert(pars.c); // ['d', 'e']
alert(pars['f[]']); // ['g']
alert('h' in pars); // false
If you don't need to read multiple values for a parameter, you could just do lookup[name]= value instead of the if...[]...push dance, to return single string values in the lookup instead of lists.

Categories

Resources