Parse url with arrays in javascript - javascript

I have input url from GET method in the following format
rec_test.html?emotion=Happy&myInputs_1%5B%5D=things&myInputs_1%5B%5D=are&myInputs_1%5B%5D=working&myInputs_2%5B%5D=i&myInputs_2%5B%5D=hope&myInputs_3%5B%5D=so
I am trying to parse it with the following code:
function getParameterByName(name){
var url = window.location.search;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
but when I pass myInputs_1 to the function, it returns null.
I somehow plan on generating the output in the format:
myInput_1 = ['things', 'are', 'working']
myInput_2 = ['i', 'hope']
myInput_3 = ['so']
but I am not able to extract the individual values. Is there a way to achieve the desired output?
edit_1
I learned that %5B is [ and %5D is ], but even if I pass myInput_1[] as parameter to the function, it still returns null, I have no idea why

You could use the URLSearchParams object of a URL instance:
s = "http://example.com/rec_test.html?emotion=Happy&myInputs_1%5B%5D=things&myInputs_1%5B%5D=are&myInputs_1%5B%5D=working&myInputs_2%5B%5D=i&myInputs_2%5B%5D=hope&myInputs_3%5B%5D=so"
url = new URL(s)
searchParams = url.searchParams
console.log(searchParams.getAll("myInputs_1[]"))
// ["things", "are", "working"]

You need to do a while loop when using .exec to find successive matches. Also, I simplified your regex.
function getParameterByName(name){
var url = decodeURIComponent(window.location.search);
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "=([^&#]*)", 'g');
var match, result = [];
while ((match = regex.exec(url)) !== null)
result.push(match[1]);
return result;
}
I suggest you go with Jean's answer unless you browser compatibility matters to you.

Non regex way
function getParamByName(name){
var value = []
paramsArray = decodeURIComponent(window.location.search).split("?")[1].split("&")
paramsArray.forEach(function(d){
if(d.indexOf(name) > -1){
value.push(d.split("=")[1])
}
})
return value;
}

Related

Extract domain from a string using Javascript?

I have an string which include many website url but i want to extract the only url that is out side these bracket [ ].
Can someone correct this ?
Note : Output Must be www.google.com and it not necessary that domain name outside [ ] will come at the end of string.
var str = '[[www.abc.com/corporate/partner/just-a-test]]acdascvdvsa.1563e24e32e42|[[www.abc.com/corporate/partner/just-a-test]]1563e24e32e42.1563e24e32e42|[[www.abc.com/instruments/infrared-guided-measurement/]]www.google.com&1566805689640.1566806059701.3';
// String can include https and instead of .com there can be .in
var arr = str.split("|");
function domainName(str) {
var match = str.match(/^(?:https?:\/\/)?(?:w{3}\.)?([a-z\d\.-]+)\.(?:[a-z\.]{2,10})(?:[\w\.-]*)*/);
if (match != null && match.length > 0) {
return match;
} else {
return null;
}
}
var domainname = domainName(str);
var domain = domainname;
console.log(domain);
Replace all occurrences of [[, followed by non-brackets, followed by ]] with a space::
var str = '[[www.abc.com/corporate/partner/just-a-test]]acdascvdvsa.1563e24e32e42|[[www.abc.com/corporate/partner/just-a-test]]1563e24e32e42.1563e24e32e42|[[www.abc.com/instruments/infrared-guided-measurement/]]www.google.com&1566805689640.1566806059701.3';
const result = str.replace(/\[\[[^[\]]*\]\]/g, ' ');
console.log(result);
Then you can search for URLs in the replaced string.
As CertainPerformance Suggest you can exclude the url that is in [ ] using replace then by using regex you can extract the domain name. Below is the code :
var str = '[[www.abc.com/corporate/partner/just-a-test]]acdascvdvsa.1563e24e32e42|[[www.abc.com/corporate/partner/just-a-test]]1563e24e32e42.1563e24e32e42|[[www.abc.com/instruments/infrared-guided-measurement/]]www.google.com&1566805689640.1566806059701.3';
var str = str.replace(/\[\[[^[\]]*\]\]/g, '');
var ptrn = /^(?:https?:\/\/)?(?:w{3}\.)?([a-z\d\.-]+)\.(?:[a-z\.]{2,10})(?:[\w\.-]*)*/g;
var i, value, domain, len, array;
array = str.split("|");
len = array.length;
for(i=0; len > i; i++) {
value = array[i].match(ptrn);
if (value !== null) {
domain = value;
}
else {
domain = "Not Found";
}
}
document.write("Domain is = ", domain);
Two main steps:
Create a regular expression that matches your desired pattern.
Use String.match()
Example:
// match all URLs
// let regex = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+#)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+#)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%#\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/g;
// match only the URL outside of the brackets
let regex = /(((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+#)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+#)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%#\.\w_]*)#?(?:[\.\!\/\\\w]*))?))(([^[\]]+)(?:$|\[))/g;
function getUrlsFromText(input) {
return input.match(regex);
}
console.log(getUrlsFromText('[[www.abc.com/corporate/partner/just-a-test]]acdascvdvsa.1563e24e32e42|[[www.abc.com/corporate/partner/just-a-test]]1563e24e32e42.1563e24e32e42|[[www.abc.com/instruments/infrared-guided-measurement/]]www.google.com&1566805689640.1566806059701.3'));
Note that I borrowed the URL matching part of the regular expression from here. If you don't want the query string to be included (as it is on the google.com match), you can modify the regex as desired.
this can be achieve by split
var str = '[[www.abc.com/corporate/partner/just-a-test]]acdascvdvsa.1563e24e32e42|[[www.abc.com/corporate/partner/just-a-test]]1563e24e32e42.1563e24e32e42|[[www.abc.com/instruments/infrared-guided-measurement/]]www.google.com&1566805689640.1566806059701.3';
let ans=str.split("]")[6]
let finalAns=ans.split("&")[0]
console.log(finalAns)
var dirtySource = "https://example.com/subdirectory";
var dirtyPos = dirtySource.indexOf("://"); // works for http and https
var cleanSource = dirtySource.substr(dirtyPos+3);
cleanSource = cleanSource.split("/")[0]; // trim off subdirectories

Regex to get a specific parameter from a URL

assume that we have a URL like this
http://localhost:8080/dev.html?organization=test&location=pr&lang=fr
I'd like to make a regex that takes the organization=test only so that I store it into a var.
So in case I have http://localhost:8080/dev.html?organization=test, I get the organization=test.
http://localhost:8080/dev.html?lang=fr&organization=test, I get organization=test.
No matter how the URL is formed or the order of the parameters, I get
organization=<organization>
Thank you
Why use RegEx or split ? Try this:
function getOrganization(){
return new URLSearchParams(location.search).get('organization')
}
(requires a polyfill for the URL API in IE)
You can use this function, assuming the parameter name does not even if the parameter does contain any characters considered special within RegExp:
function getParam(url, name, defaultValue) {
var a = document.createElement('a');
a.href = '?' + unescape(String(name));
var un = a.search.slice(1);
var esc = un.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&');
var re = new RegExp('^\\?&*(?:[^=]*=[^&]*&+)*?(' + esc + ')=([^&]*)');
a.href = url;
var query = a.search;
return re.test(query) ? query.match(re).slice(1).map(decodeURIComponent) : [un, defaultValue];
}
var url = 'http://localhost:8080/dev.html?lang=fr&organization=test&crazy^ ()*key=cool';
console.log(getParam(url, 'organization'));
console.log(getParam(url, 'lang'));
console.log(getParam(url, 'crazy^ ()*key'));
console.log(getParam(url, escape('crazy^ ()*key')));
console.log(getParam(url, encodeURIComponent('crazy^ ()*key')));
console.log(getParam(url, 'foo', 'bar'));
RegExp escape method borrowed from How to escape regular expression in javascript?
Usage
getParam(url, name[, defaultValue])
url - A well-formed URL
name - The parameter name to search
defaultValue (optional) - If not found, what value to default to. If not specified, defaultValue is undefined
return - [ unescape(name), found ? stringValue : defaultValue ]
Why use regex? Try this.
function getOrganization(){
var params = location.search.split('?')[1].split('&');
for(var i = 0; i < params.length; i++){
if(params[i].split('=')[0] == 'organization') return params[i].split('=')[1];
}
}

Retrieve number from string via JS regex

I'm trying to retrieve a certain number from a string. But i can't figure out how to isolate the part i need.
The string:
https://intra.site.com/departments/travel/Lists/Booking/fd_Item_Display.aspx?List=8af14ed7-3bde-4ec0-b62a-9516324c967e&ID=15&Source=https%3A%2F%2Fintra%2Emonjasa%2Ecom%2Fdepartments%2Ftravel%2FPages%2Fdefault%2Easpx&ContentTypeId=0x0100B7DC1AFF519B6343BC8014EB1910DFAB
I need the number after ID=.
I did try to use string.replace() without luck.
How could I do this with regex?
Check this out :
function getParameterByName(url, parameter) {
var regex = new RegExp("[\\?&]" + parameter + "=([^&#]*)"),
results = regex.exec(url);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var url = 'https://intra.site.com/departments/travel/Lists/Booking/fd_Item_Display.aspx?List=8af14ed7-3bde-4ec0-b62a-9516324c967e&ID=15&Source=https%3A%2F%2Fintra%2Emonjasa%2Ecom%2Fdepartments%2Ftravel%2FPages%2Fdefault%2Easpx&ContentTypeId=0x0100B7DC1AFF519B6343BC8014EB1910DFAB';
var parameter = 'ID';
console.log( getParameterByName(url, parameter) );
// Log => 15
You can use:
var str = 'https://intra.site.com/departments/travel/Lists/Booking/fd_Item_Display.aspx?List=8af14ed7-3bde-4ec0-b62a-9516324c967e&ID=15&Source=https%3A%2F%2Fintra%2Emonjasa%2Ecom%2Fdepartments%2Ftravel%2FPages%2Fdefault%2Easpx&ContentTypeId=0x0100B7DC1AFF519B6343BC8014EB1910DFAB';
var id = (str.match(/&ID=([^&]*)/i) || ['', ''])[1];
//=> 15
Try this. Easier to understand.
function getID()
{
var str = "https://intra.site.com/departments/travel/Lists/Booking/fd_Item_Display.aspx?List=8af14ed7-3bde-4ec0-b62a-9516324c967e&ID=15&Source=https%3A%2F%2Fintra%2Emonjasa%2Ecom%2Fdepartments%2Ftravel%2FPages%2Fdefault%2Easpx&ContentTypeId=0x0100B7DC1AFF519B6343BC8014EB1910DFAB";
var id = str.match(/ID=(\d*)/)[1];
alert(id);
}
<input type="button" onclick="getID()" value="Click me">

Get values of all the same parameter from url in jQuery

I have an url have contain two parameters.
Ex: https://www.google.com.vn/search?q=news&oq=news&aqs=chrome..69i57j69i60l3.299j0j4&sourceid=chrome&es_sm=93&ie=UTF-8#q=bbc
Parameter 1: q=news
Parameter 2:q=bbc
I want to get all value have the same parameter, but I can only get value in first the parameter.
This is my code:
function getParameterByName(name, url) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&#]" + name + "=([^&#]*)"),
results = regex.exec(url);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Use $(location).attr('href'); and parse through the parameters yourself
what i have tried is only IDEA of how you can get all paremater.
var a="https://www.google.com.vn/search?q=news&oq=news&aqs=chrome..69i57j69i60l3.299j0j4&sourceid=chrome&es_sm=93&ie=UTF-8#q=bbc"
var b= a.split("?")[1]
b.split("&")
By this technique you will get all parameter.
You need to convert this code to your required code.
The first q is in querystring, the second one is in hash. You should parse them in JavaScript:
QueryString
// the method is taken from http://stackoverflow.com/a/3855394/3971911
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
Hash
// the method is taken from http://stackoverflow.com/a/11920807/3971911
function getHashValue(key) {
return location.hash.match(new RegExp(key+'=([^&]*)'))[1];
}
Now you can use them like this:
alert(qs['q']); // news
alert(getHashValue('q')); // bbc
try this:
function getParameterByName(name, url,position) {
url=position==1?url:url.substr(url.lastIndexOf('#'));
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&#]" + name + "=([^&#]*)"),
results = regex.exec(url);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var url='https://www.google.com.vn/search?q=news&oq=news&aqs=chrome..69i57j69i60l3.299j0j4&sourceid=chrome&es_sm=93&ie=UTF-8#q=bbc';
alert(getParameterByName('q',url,1));
alert(getParameterByName('q',url,2));
Demo
Other than an exercise in coding, you're probably better off using existing code.
Something like:
https://github.com/sindresorhus/query-string
Pros:
It has tests
It's had more useful eyes cast over it (guessing here).
The people that have likely contributed to it will probably have used it.
If you find an issue with it, those people involved will have a keen interest in solving the problem as they're likely using it.
Cons:
None! :D

How do I extract "search term" from URLs?

How do I extract "test" from the following URL?
http://www.example.com/index.php?q=test&=Go
I've found the a script to extract the path (window.location.pathname), but I can't find or figure out how to extract or split the URL.
-ben
var m = window.location.search.match(/q=([^&]*)/);
if (m) {
alert(m[1]); // => alerts "test"
}
var myURL = 'http://www.example.com/index.php?q=test&=Go';
function gup( name ) //stands for get url param
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( myURL );
if( results == null )
return "";
else
return results[1];
}
var my_param = gup( 'q' );
Here is the jsfiddle
Or you can use jQuery's plugin:
URL Parser JQuery
If you just want the value of the first term, then:
function getFirstSeachValue() {
var s = window.location.search.split('&');
return s[0].split('=')[1];
}
If you want the value of the 'q' term, regardless of where it is in the search string, then the following returns the value of the passed term or null if the term isn't in the search string:
function getSearchValue(value) {
var a = window.location.search.replace(/^\?/,'').split('&');
var re = new RegExp('^' + value + '=');
var i = a.length;
while (i--) {
if (re.test(a[i])) return a[i].split('=')[1];
}
return null;
}
Both are just examples of course and should test results along the way to prevent unexpected errors.
--
Rob

Categories

Resources