get data from url - javascript

i took a ready script from here, How to read GET data from a URL using JavaScript? and can't make it work, what im doing wrong?
here is my script:
function getUrlParam(param)
{
param = param.replace(/([\[\](){}*?+^$.\\|])/g, "\\$1");
var regex = new RegExp("[?&]" + param + "=([^&#]*)");
var url = decodeURIComponent(window.location.href);
var match = regex.exec(url);
return match ? match[1] : "";
}
var param = getUrlParam("process_number");
alert(param);
and here is my link:
http://erp.micae.com/index.cfm?fuseaction=objects.popup_print_files&process_number=SER-498&action_type=141&action_id=289&action_row_id=32&print_type=192
thx for the help!
Sorry guys, forgot to mantion that my page is working in a frame, that why it can't get the data from url i want :)

Since you're in a frame, if you need to get the href from the main window, do this:
var href = window.top.location.href;
Then process it.

That code has to run from the page whose URL you're mining for parameter values. In other words, it operates only on the current URL of the page it's on. It works fine.
If you want a function that gives you parameter values given an arbitrary URL, you'd just need to add an additional parameter:
function getUrlParam(param, url) {
param = param.replace(/([\[\](){}*?+^$.\\|])/g, "\\$1");
var regex = new RegExp("[?&]" + param + "=([^&#]*)");
url = url || decodeURIComponent(window.location.href);
var match = regex.exec(url);
return match ? match[1] : "";
}
alert(getUrlParam("process_number", "http://erp.micae.com/index.cfm?fuseaction=objects.popup_print_files&process_number=SER-498&action_type=141&action_id=289&action_row_id=32&print_type=192"));

Related

How to remove `&` sign and all text after that from url

I have this URL
https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request
Here I am getting sys_id two times with different parameters. So I need to remove the second & sign and all text after that.
I tried this
location.href.split('&')[2]
I am sure it doesn't work. Can anyone provide some better solution?
Firstly, you should split the string into an array then use slice to set the starting index number of the element which is 2 in your case and then join the array again into the string.
Read more about these methods JavaScript String split() Method, jQuery slice() Method and JavaScript Array join() Method
var url = 'https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
url = url.split("&").slice(0,2).join("&");
console.log(url);
Maybe like this:
var url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
var first=url.indexOf('&');
var second=url.indexOf('&',first+1);
var new_url=url.substring(0,second);
console.log(new_url);
You need to find the 2nd occurrence of &sys_id. From there onwards remove all text.
Below is working code:
let url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
let str1=url.indexOf('&sys_id');
let str2=url.indexOf('&sys_id',str1+1);
console.log(url.substring(0,str2));
This is a bit more verbose, but it handles all duplicate query params regardless of their position in the URL.
function removeDuplicateQueryParams(url) {
var params = {};
var parsedParams = '';
var hash = url.split('#'); // account for hashes
var parts = hash[0].split('?');
var origin = parts[0];
var retURL;
// iterate over all query params
parts[1].split('&').forEach(function(param){
// Since Objects can only have one key of the same name, this will inherently
// filter out duplicates and keep only the latest value.
// The key is param[0] and value is param[1].
param = param.split('=');
params[param[0]] = param[1];
});
Object.keys(params).forEach(function(key, ndx){
parsedParams += (ndx === 0)
? '?' + key +'='+ params[key]
: '&' + key +'='+ params[key];
});
return origin + parsedParams + (hash[1] ? '#'+hash[1] : '');
}
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff') );
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff#withHash') );
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
url = url.slice(0, url.indexOf('&', url.indexOf('&') + 1));
console.log(url);
Try this :)
Try this:
var yourUrl = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
var indexOfFirstAmpersand = yourUrl.search("&"); //find index of first &
var indexOfSecondAmpersand = indexOfFirstAmpersand + yourUrl.substring((indexOfFirstAmpersand + 1)).search("&") + 1; //get index of second &
var fixedUrl = yourUrl.substring(0, indexOfSecondAmpersand)
$(".answer").text(fixedUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="answer">
</p>
You can manipulate the url using String.prototype.substring method. In the example below I created a function that takes a url string and checks for a duplicate parameter - it returns a new string with the second occurrence removed.
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request";
function stripDuplicateUrlParameter(url, parameterName) {
//get the start index of the repeat occurrance
var repeatIdx = url.lastIndexOf('sys_id');
var prefix = url.substring(0, repeatIdx);
var suffix = url.substring(repeatIdx);
//remove the duplicate part from the string
suffix = suffix.substring(suffix.indexOf('&') + 1);
return prefix + suffix;
}
console.log(stripDuplicateUrlParameter(url));
This solves your specific problem, but wouldn't work if the parameter occurred more than twice or if the second occurrence of the string wasn't immediately following the first - you would probably write something more sophisticated.
As someone already asked - why is the url parameter being duplicated in the string anyway? Is there some way to fix that? (because the question asked seems to me to be a band-aid solution with this being the root issue).

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.

How can I remove part of a url after a specific keyword?

For example:
example.com/fun/browse/apples/bananas
example.com/browse/gerbals/cooties
How can I find the keyword "browse", regardless of where it is in the url, and remove the following url part. In the above cases that would be "apples" and "gerbals"
I tried spliting it by the "/" and getting the indexOf browse, then removing the next item, but I cant seem to join everything together because that creates a double "//" in the new url.
Any help would be appreciated.
Javascript and jQuery both ok.
NOTE: I do not want to remove any other part of the url. I want to keep everything. I want to only remove the part of the url immediately after browse.
Your question is unclear but let's try :
var s = 'example.com/fun/browse/apples/bananas';
s.replace(/(\/browse)\/[^\/]+/, '$1'); // "example.com/fun/browse/bananas"
Also check this helper :
function removeAfter(s, keyword) {
return s.replace(
new RegExp('(\/' + keyword + ')\/[^\/]+'), '$1'
);
}
Usage :
var s = 'example.com/browse/gerbals/cooties';
removeAfter(s, 'browse'); // "example.com/browse/cooties"
removeAfter(s, 'gerbals'); // "example.com/browse/gerbals"
Demo : http://jsfiddle.net/wared/VRJtL/.
remove browser by using .splice() & rejoin it.
var arr = "example.com/fun/browse/apples/bananas".split('/');
var index = arr.indexOf("browse");
arr.splice(index+1,1); //removes apples
var URL = arr.join('/'); //joins back
result: "example.com/fun/browse/bananas"
Split the URL on the Keyword...
example:
var url = "http://www.foo.com/bar/alpha/beta";
var keyword = "alpha";
var result = url.split(keyword)[0];
//result = "http://www.foo.com/bar/" + keyword;
//adding the keyword is if you need the keyword in your response.
If you're not trying to remove 'fun' part, it's really simple:
var url = 'example.com/fun/browse/apples/bananas';
var result = url.replace(/browse\/[a-zA-Z\/]+/, 'browse/gerbals/cooties');
I'll throw out another option, just to make it interesting. :)
var url = "http://example.com/fun/browse/apples/bananas";
var targetWord = "browse";
var regexPattern = new RegExp("(^.*" + targetWord + "/?)[^/]*/?(.*$)");
var newURL = "";
var matchedURLparts = regexPattern.exec(url);
if (matchedURLparts) {
newURL = (matchedURLparts.length > 2) ? matchedURLparts[1] + matchedURLparts[2] : matchedURLparts[1];
}
else {
newURL = url;
}

Get the last part of an url in Javascript

Using the following URL example, how would I get the obtain the username from it?
http://www.mysite.com/username_here801
A regex solution would be cool.
The following sample only gets the domain name:
var url = $(location).attr('href');
alert(get_domain(url));
function get_domain(url) {
return url.match(/http:\/\/.*?\//);
}
jQuery solutions are also acceptable.
var url = "http://www.mysite.com/username_here801";
var username = url.match(/username_(.+)/)[1];
http://jsfiddle.net/5LHFd/
To always return the text directly after the slash that follows the .com you can do this:
var url = "http://www.mysite.com/username_here801";
var urlsplit = url.split("/");
var username = urlsplit[3];
http://jsfiddle.net/5LHFd/2/
You can access it with document.location.pathname
If a RegEx solution is acceptable, you could try:
function get_path(url) {
// following regex extracts the path from URL
return url.replace(/^https?:\/\/[^\/]+\//i, "").replace(/\/$/, "");
}
You could use your getDomain() function to find out where your pathname start.:
function getUsername(url){
var position = getDomain(url).length + 1;
return url.slice(position);
}

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