How to parse url to get desired value [duplicate] - javascript

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');

Related

Check whether an array includes a string but ignore rest other letters in that string [duplicate]

This question already has answers here:
Is there a javascript method to find substring in an array of strings?
(5 answers)
How to check if a string contains text from an array of substrings in JavaScript?
(24 answers)
Closed 4 years ago.
I have a variable like,
var url = "/login/user";
And I have an array like,
var x = ["login", "resetpassword", "authenticate"];
Now I need to check, whether that url string is present in an array of string. As we can see that login is present in an array but when i do x.indexOf(url), it always receive false because the field url has rest other letters also. So now how can I ingnore those letters while checking a string in an array and return true?
Use .some over the array instead:
var url = "/login/user";
var x = ["login", "resetpassword", "authenticate"];
if (x.some(str => url.includes(str))) {
console.log('something in X is included in URL');
}
Or, if the substring you're looking for is always between the first two slashes in the url variable, then extract that substring first, and use .includes:
var url = "/login/user";
var x = ["login", "resetpassword", "authenticate"];
var foundStr = url.split('/')[1];
if (x.includes(foundStr)) {
console.log('something in X is included in URL');
}
One way is to split url with / character and than use some
var url = "/login/user";
var x = ["login", "resetpassword", "authenticate"];
let urlSplitted = url.split('/')
let op = urlSplitted.some(e=> x.includes(e))
console.log(op)
You could join the given words with a pipe (as or operator in regex), generate a regular expression and test against the string.
This works as long as you do not have some characters with special meanings.
var url = "/login/user",
x = ["login", "resetpassword", "authenticate"];
console.log(new RegExp(x.join('|')).test(url));

Split URL string to get each parameter value in javascript [duplicate]

This question already has answers here:
How to convert URL parameters to a JavaScript object? [duplicate]
(34 answers)
Closed 8 years ago.
var url = "journey?reference=123line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC"
How can I split the string above so that I get each parameter's value??
You could use the split function to extract the parameter pairs. First trim the stuff before and including the ?, then split the & and after that loop though that and split the =.
var url = "journey?reference=123line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC";
var queryparams = url.split('?')[1];
var params = queryparams.split('&');
var pair = null,
data = [];
params.forEach(function(d) {
pair = d.split('=');
data.push({key: pair[0], value: pair[1]});
});
See jsfiddle
Try this:
var myurl = "journey?reference=123&line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC";
var keyval = myurl.split('?')[1].split('&');
for(var x=0,y=keyval.length; x<y; x+=1)
console.log(keyval[x], keyval[x].split('=')[0], keyval[x].split('=')[1]);
to split line in JS u should use:
var location = location.href.split('&');

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/

JS - read value of submitted form [duplicate]

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.

Grab url parameter with jquery and put into input

I am trying to grab a specific paramater from a url such as www.internets.com?param=123456
I am trying it with something like this..
$j.extend({
getUrlVars: function(){
return window.location.href.slice(window.location.href.indexOf('?')).split(/[&?]{1}[\w\d]+=/);
}
});
var allVars = $j.getUrlVars('param');
The weird thing is the variable is returning a comma so in this example it looks like ,123456
Where is that coming from?!
split returns an array of substrings, so the comma is coming from the serialization of the array.
Have a look here: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
This seems to work for me.
You're asking the javascript to split the string into an array based on the rules in your regex, so the string "?param=123456" turns into an array where everything up to the = is simply a separator, so it sees two keys: an empty string and 123456.
EDIT - You can still use split, just use a different separator. The indexOf is telling it to look at the substring after the position of the '?', so if you split on '=' it would provide an array where one value is a parameter name (possibly with a '?' or '&', so just remove it) and the next value is the value sent in after the equal sign.
You can also get a little more in depth with your regex and processing like so:
var q = window.location.search; // returns everything after '?'
var regEx = /[^?& =]([\w]*)[^!?& =]/g;
var array = q.match(regEx);
var vars = new Array();
for (var i = 0; i < array.length; i++) {
if ((i % 2) == 0) {
vars[array[i]] = array[i + 1];
}
}
Which will leave you with an array where the keys are the param names, and their values are the associated values from the query string.

Categories

Resources