Get values of all the same parameter from url in jQuery - javascript

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

Related

Javascript regex to get param value

I'm working on a code base someone else built and the search function uses this to get the parameter from the url to place as a value to search against. I've tried re-writing it, modifiying it, and everything else possible and can't figure out what is going on with the reutrn value from the function.
Here's the function
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
console.log(name);
var regex = new RegExp("[\\?&#;]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
console.log(results);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var part = getParameterByName('part_name');
The value of location.search is ?part_number=1234&go=GO
Then in the input box part_name if I type 1234 to be the value of the passed in parameter it will only show 12. However typing in other random numbers it will sometimes show them all correctly. If I type 124 as the search param then it displays correctly as searching against 124.
Is there something wrong with one of these regex statments that could be causing this, or is this something on the server side? The PHP seems fine on the backend but I'm not savvy on the Regex used in the Javascript code.
EDIT:
A testing snippet:
function getParameterByName(loc, name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
document.getElementById("res").innerHTML += "Name: " + name + " - ";
var regex = new RegExp("[\\?&#;]" + name + "=([^&#]*)"),
results = regex.exec(loc);
document.getElementById("res").innerHTML += results + "<br/>";
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var part = getParameterByName('?part_number=1234&go=GO', 'part_number');
var part2 = getParameterByName('?part_name=12&go=GO', 'part_name');
<div id="res"/>

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">

JavaScript not working with putting innerhtml from databases

i have builded a java script code(here he is) :
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];
}
this code gets the permart from the head of the url and puts it into a span, now the problem is when i do "Something like that" its happend to get like that :
%22hey%20hey%22..
what can i do?
EDIT1:
I mean its takes parameters like that www.google.co.il?per="grg" and when i do www.google.co.il?per="Hey Hey" its like that %22hey%20hey%22.
try with
return decodeURIComponent(results[1]);
You will get decoded string (Readable string in the sense)

How to get parameter like (parameter name contains) with javascript?

i am using the following method to get parameter by name:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
and i was wondering how to change it to get parameter that contains some string for example, i want to get the parameter that contains the word "document" but the whole parameter name is not "document".
please advise, thanks.
Like this?
val = location.search.match(/document.*?=([^&]*)/)[1]
Although I'd rather use a function that converts the whole query string into an object (like this one) and simply apply a filter afterwards:
params = urlParams()
ks = Object.keys(params).filter(function(k) { return k.indexOf("document") >= 0 })
if(ks)
value = params[ks[0]];
This way you can easily support multiple params (as in document1=foo&document2=bar) and avoid ugly dynamic regexp construction.
In older browsers you can use this instead of Object.keys/filter:
ks = []
for(var k in params)
if(k.indexOf("document") >= 0)
ks.push(k);
Suggestion:
function getParameterByPartialName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&][^&#]*" + name + "[^=]*=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
This however, will return only the 1st match, there might be more parameters that have a similar name. You could return an array of key-value pairs for all matches.

Remove sections of url to only keep file name

I want to remove everything in the URL and only keep the name of the file/image. The URL is a dynamic input/variable.
Code:
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
str = str.replace("http://website.com/sudir/sudir/subdir/", "")
.replace(/[^a-z\s]/gi, ' ').replace("_", " ")
.replace("subdir", "").toLowerCase().slice(0,-4);
You can do this easily with lastIndexOf():
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
str.substring(str.lastIndexOf("/") + 1)
//"Image_01.jpg"
This function will give you the file name,
function GetFilename(url)
{
if (url)
{
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1)
{
return m[1];
}
}
return "";
}
From How to catch the end filename only from a path with javascript?
var filename = path.replace(/.*\//, '');
From Getting just the filename from a path with Javascript
var fileNameIndex = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(fileNameIndex);
I know you haven't specified the exact URL format and whether this may be possible in your situation, but this may be a solution worth considering.
Javascript
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg?x=y#abc";
console.log(str.split(/[?#]/)[0].split("/").slice(-1)[0]);
str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
console.log(str.split(/[?#]/)[0].split("/").slice(-1)[0]);
On jsfiddle
You can always Regex to extract data from strings:
The Regex to extract data from URL:
"http://website.com/sudir/sudir/subdir/(?<FileName>[0-9A-Za-z._]+)"

Categories

Resources