JQuery: Retrieve data from URL - javascript

I am 'sending' some data in a url:
foo.htm?mydata
From searching around I know that I must use something like:
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
But I am a bit perplexed by this. Could someone help me out in deciphering this at all I simply want the end result to be placing mydata in a var, eg:
var newvar = mydata
Thanks heaps in advance!

The getParameterByName function (I assume you got it from here), is written to retrieve a query string value. This means, you can access data from the URL when it looks like this:
yourdomain.com/index.html?key=value&anotherkey=anothervalue
Now you can do this:
var firstKey = getParameterByName("key");
var secondKey = getParameterByName("anotherkey");
As described in your question, you don't have key/value pairs. If this is the case, and you only need the part after the ?, simply use the following by using the split method:
var newvar = document.URL.split("?")[1];
I do suggest you use the key/value method though, in case you want to pass on more variables in the future.

Maybe this library is interesting if you are in need of a lot of uri parsing:
https://github.com/medialize/URI.js

Related

Javascript - Get substring that comes after "string1" and before "string2"

When making a fetch to a certain URL, I am getting an HTML page in the format of text as I wanted.
Inside of it, there are plenty of id=(...)" and I require one of them
So I am asking, how could I get an array with all the strings that come after "id=" and before the " " "?
I made some tries such as :
var startsWith = "id="
var endsWith = "\""
var between = fullString.slice(fullString.indexOf(startsWith), fullstring.indexOf(endsWith))
but couldn't get it to work.
Any suggestions are welcome
you can use the following regex: /id=\"(.*?)\"/gmi.
The code will be as such:
fullString.match(/id=\"(.*?)\"/gmi)
The result will be an array of id="your id"
and then you can do the following:
var between = fullString.match(/id=\"(.*?)\"/gmi).map(str => str.substr(str.indexOf('id=\"') + 'id=\"'.length).slice(0, -1))
Why you dont use a plugin like jquery? Please refer to this example:
var fullString = "<y>your cool html</y>";
var $html = $(fullString);
var stuffInside = $(html).find('#yourId');
console.warn('stuffInside:', stuffInside.html());

Trouble reading a query string in a Query String?

I have a URL in a query string value that is similar to this one:
example.com/?p1=a1&p2=a2
And I have a query sting on my website that takes the URL and redirects to a certain page. Like this:
mysite.com/?url=example.com/?p1=a1&p2=a2
But the query string is misinterpreted. How can I separate the query string in the value URL from the actual URL? I have tried encoding the question marks and ampersands, but the page is missing the content from the value URL.
EDIT:
This is how I get the URL, through a javascript:
function nameps(url) {
url = url.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + url + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null) return "";
else {
return results[1];
}
}
how does the url value get passed to the javascript? That is the place you should be url-encoding the whole URL, to make
example.com/?p1=a1&p2=a2
be inputted into the javascript on your site as
example.com%2F%3Fp1%3Da1%26p2%3Da2
You will need to adjust your regex in your javascript to deal with this change in format or alternatively use a javascript url decoding function such as decodeuri .
decodeURI()
such as on your site:
function nameps(url) {
url = decodeURI(url); ///new line decodes the previously encoded URL
url = url.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + url + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null) return "";
else {
return results[1];
}
}
This would also involve however you pass the url value to the function above, would have to include the line :
url = encodeURI(url);
In order to correctly encode and format the address given.
I wouldn't try to get too complicated with the query string. Instead of this:
mysite.com/?url=example.com/?p1=a1&p2=a2
I would do this:
mysite.com/?url=example.com&p1=a1&p2=a2
Then I would parse it up and rebuild the secondary url from the components.
Trying to pack a query string in a query string is asking for trouble. I wouldn't waste any time trying to get it to work that way.

Parameter from URL Javascript - Form: /index.html#/?id=1426591453147

im trying to get a parameter from the current url using JavaScript or jQuery.
The URL looks like this:
http://my-site.com/index.html#/?id=1426591453147
or
http://my-site.com/#/?id=1426591453147
I tried a few codes with "location.search", but location.search return an empty string on my urls.
Does anyone know a good solution to this?
EDIT:
I ended up using this:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?]" + name + "=([^&#]*)"),
results = regex.exec(location.hash);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Something like this? (works with your specific case)
"http://my-site.com/index.html#/?id=1426591453147".replace(/^.*?\.com(.*?)$/i, '$1'); // "/index.html#/?id=1426591453147"
"http://my-site.com/#/?id=1426591453147".replace(/^.*?\.com(.*?)$/i, '$1'); // "/#/?id=1426591453147"
So,
location.href.replace(/^.*?\.com(.*?)$/i, '$1');

Capture value out of query string with regex?

I am trying to select just what comes after name= and before the & in :
"/pages/new?name=J&return_url=/page/new"
So far I have..
^name=(.*?).
I am trying to return in this case, just the J, but its dynamic so it could very several characters, letters, or numbers.
The end case situation would be allowing myself to do a replace statement on this dynamic variable found by regex.
/name=([^&]*)/
remove the ^ and end with an &
Example:
var str = "/pages/new?name=J&return_url=/page/new";
var matches = str.match(/name=([^&]*)/);
alert(matches[1]);
The better way is to break all the params down (Example using current address):
function getParams (str) {
var queryString = str || window.location.search || '';
var keyValPairs = [];
var params = {};
queryString = queryString.replace(/.*?\?/,"");
if (queryString.length)
{
keyValPairs = queryString.split('&');
for (pairNum in keyValPairs)
{
var key = keyValPairs[pairNum].split('=')[0];
if (!key.length) continue;
if (typeof params[key] === 'undefined')
params[key] = [];
params[key].push(keyValPairs[pairNum].split('=')[1]);
}
}
return params;
}
var url = "/pages/new?name=L&return_url=/page/new";
var params = getParams(url);
params['name'];
Update
Though still not supported in any version of IE, URLSearchParams provides a native way of retrieving values for other browsers.
The accepted answer includes the hash part if there is a hash right after the params. As #bishoy has in his function, the correct regex would be
/name=([^&#]*)/
Improving on previous answers:
/**
*
* #param {string} name
* #returns {string|null}
*/
function getQueryParam(name) {
var q = window.location.search.match(new RegExp('[?&]' + name + '=([^&#]*)'));
return q && q[1];
}
getQueryParam('a'); // returns '1' on page http://domain.com/page.html?a=1&b=2
here is the full function (tested and fixed for upper/lower case)
function getParameterByName (name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name.toLowerCase() + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search.toLowerCase());
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
The following should work:
\?name=(.*?)&
var myname = str.match(/\?name=([^&]+)&/)[1];
The [1] is because you apparently want the value of the group (the part of the regex in brackets).
var str = "/pages/new?name=reaojr&return_url=/page/new";
var matchobj = str.match(/\?name=([^&]+)&/)[1];
document.writeln(matchobj); // prints 'reaojr'
Here's a single line answer that prevents having to store a variable (if you can't use URLSearchParams because you still support IE)
(document.location.search.match(/[?&]name=([^&]+)/)||[null,null])[1]
By adding in the ||[null,null] and surrounding it in parentheses, you can safely index item 1 in the array without having to check if match came back with results. Of course, you can replace the [null,null] with whatever you'd like as a default.
You can get the same result with simple .split() in javascript.
let value = url.split("name=")[1].split("&")[0];
This might work:
\??(.*=.+)*(&.*=.+)?

How to get url params with javascript

Let's say I have the following url:
something.com/messages/username/id
How can I get the username or id?
You can use String.split for that:
var parts = window.location.href.split('/'); # => ["http:", "", "something.com", "messages", "username", "id"]
var username = parts[4];
var id = parseInt(parts[5]);
I guess you could use the window.location.href to get the URL and then string.split() the URL on /.
var urlParts = window.location.href.split("/");
var username = urlParts[4];
var id = urlParts[5];
I actually just had to deal with the other day. When you're accessing the cached version of some of our pages, the query string is actually part of the URL path. But if you're trying to avoid the cache, you use a query string.
Given one of the answers from How to get the value from the GET parameters? here's what I'm using to partially normalize access.
The router that takes the response does _.isArray() (we're built on top of backbone, so we have underscore available) and handles pulling the data out of the object or array in a different manner.
The slice at the end gets rid of the two "" since we're not using documents, just directories and our URLs start and end with /. If you're looking for document access, you should alter the slice accordingly.
var qs = function(){
if(window.location.search){
var query_string = {};
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q)){
query_string[d(e[1])] = d(e[2]);
}
})();
} else {
return window.location.pathname.split('/').slice(1, -1);
}
return query_string;
};
You could split your url on every '/' character like this:
var url = "something.com/messages/username/id";
var array = url.split('/');
// array[2] contains username and array[3] contains id

Categories