Retrieve number from string via JS regex - javascript

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

Related

Parse url with arrays in 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;
}

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

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

How can I get URL parameter in a jquery ready function?

I have the following:
$(document).ready(function() {
window.location.href='http://target.SchoolID/set?text=';
});
So if someone comes to a page with the above mentioned code using a url like:
Somepage.php?id=abc123
I want the text variable in the ready function to read: abc123
Any ideas?
you don't need jQuery. you can do this with plain JS
function getParameterByName( name ) //courtesy Artem
{
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 decodeURIComponent(results[1].replace(/\+/g, " "));
}
and then you can just get the querystring value like this:
alert(getParameterByName('text'));
also look here for other ways and plugins: How can I get query string values in JavaScript?
check out the answer to this questions:
How can I get query string values in JavaScript?
that'll give you the value of the id parameter from the query string.
then you can just do something like:
$(document).ready(function() {
var theId = getParameterByName( id)
var newPath = 'http://target.SchoolID/set?text=' + theId
window.location.href=newPath;
});
To help people coming after me that want to have multiple variables and to enhance Moin's answer here is the code for multiple variables:
function getParameterByName( name ) //courtesy Artem
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
{
if ((results[1].indexOf('?'))>0)
return decodeURIComponent(results[1].substring(0,results[1].indexOf('?')).replace(/\+/g, " "));
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
}

Categories

Resources