I'm using javascript and would like to take a URL string that I have and break it down into its components such as the host, path, and query arguments.
I need to do this in order to get to one of the query arguments, which is itself a URL and is thus encoded in the original URL string.
I feel like there should be an easy way to do this in Javascript. Perhaps something that looks like this:
var what_I_Want = url("http://www.domain.com?queryArg1=somequeryargument").getQueryArgumentValue("queryArg1");
The parseUri function will do everything you need
Edit
Alternatively you can get the DOM to do the hard work for you and access properties on a newly created a object for different parts of the URL.
<script type="text/javascript" language="javascript">
newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
</script>
Hope this will help..
In javascript you can do this by using split() for the params and using the location object for the protocol and domain -- like Carl suggested
Also you can use parseUri as Tak suggested
There is also a jQuery plugin which makes parsing easier if you are already using jQuery in your project: https://github.com/allmarkedup/jQuery-URL-Parser#readme
Example:
$.url('http://allmarkedup.com?sky=blue&grass=green').param('sky'); // returns 'blue'
Probably not the greatest way of doing it but a simple method to get the query string in JavaScript would be to just use something along the lines of:
a = "http://www.domain.com?queryArg1=somequeryargument";
query = a.substring(a.indexOf('?')+1);
You could then split the query up based on the &'s and again on the = to get at whatever param you need.
Sorry if this ain't very helpful as its a bit of a low tech method :P
EDIT:
Just wrote a quick little JavaScript object to get URL Query parameters for you (sort of like) in your example. Only tested it in chrome but in theory it should work :)
//Quick and dirty query Getter object.
function urlQueryGetter(url){
//array to store params
var qParam = new Array();
//function to get param
this.getParam = function(x){
return qParam[x];
}
//parse url
query = url.substring(url.indexOf('?')+1);
query_items = query.split('&');
for(i=0; i<query_items.length;i++){
s = query_items[i].split('=');
qParam[s[0]] = s[1];
}
}
//Useage
var bla = new urlQueryGetter("http://www.domain.com?queryArg1=somequeryargument&test=cheese");
alert(bla.getParam('test'));
Related
So, I'm working on a bookmarklet that takes the website url, which contains the actual text '%2F' in it, and split it there. However, because %2F represents a forward slash, it keeps splitting where there are forward slashes and not at %2F. How can I fix this?
Current Code:
javascript:(
function(){
var str = window.location.href;
var res = str.split("%2F");
alert(res); //Just here to test the output
}
)
();
Example Input:
http://blocked.com-default.ws/?oI=14697520135&type=chromium-m&url=i.imgur.com%2F4uHAdNPg.jpg
Example Output:
http:,,blocked.com-default.ws/?oI=14697520135&type=chromium-m&url=i.imgur.com%2F4uHAdNPg.jpg
Wanted Output:
http://blocked.com-default.ws/?oI=14697520135&type=chromium-m&url=i.imgur.com ,4uHAdNPg.jpg
It looks like you want you focus your splitting more to a specific portion of the location rather that the whole URL. In your case, it looks like you really want to split the value of the url variable which is found in window.location.search. You can probably accomplish close what you want if you just use that instead of window.location.href.
A better approach might be to target the actual value of the url variable.If you don't need to support IE, an easy way to get that data is to use UrlSearchParams:
const params = new URLSearchParams(window.location.search);
const url = params.get("url");
const res = url.split('%2F');
If you do need more cross browser reach, you can also do this with a simple regular expression:
const url = window.location.search.match(/url=[^&]+/)
const res = url.split('%2F');
The split works as expected:
const str = 'http://blocked.com-default.ws/?oI=14697520135&type=chromium-m&url=i.imgur.com%2F4uHAdNPg.jpg';
console.log(str.split('%2F'));
But window.location.href doesn't always return exactly the same string that is being displayed in the address bar, or encode stuff without you knowing about it. It is quite browser-dependent. For example, on chrome, you might observe this:
location.href = 'http://example.com/ xxx';
console.log(location.href); // http://example.com/%20xxx
In any case, it just looks like you're trying to manipulate your URL by hand. Don't do that. By using new URL(...), location.searchParams, decodeURIComponent, and other native APIs to easily manipulate URLs, you'll probably achieve what you're looking for in an easier and safer way ;)
For example I have a url like:
ftp://xxx:xxx#ftp.example.com/BigFile.zip
How can I get example.com from this url using javascript/jquery?
You can get the browser to parse the URL for you like this :
var a = document.createElement('a');
a.href = 'ftp://xxx:xxx#ftp.example.com/BigFile.zip';
var host = a.hostname;
That gets you the hostname, which in this case would be ftp.example.com, if for some reason you have to remove the subdomain, you can do
var domain = host.split('.');
domain.shift();
var domain = domain.join('.');
FIDDLE
Here's the different parts to a URL -> https://developer.mozilla.org/en-US/docs/Web/API/Location#wikiArticle
Here is using javascript RegExp
input = "ftp://xxx:xxx#ftp.example.com/BigFile.zip";
pattern = new RegExp(/ftp:\/\/\S+?#\S+?\.([^\/]+)/);
match = pattern.exec(input);
alert(match[1]);
You can also use i at the end of regex to make it case insensitive.
pattern = new RegExp(/ftp:\/\/\S+?#\S+?\.([^\/]+)/i);
You can use jquery like this:
var url = "ftp://xxx:xxx#ftp.example.com/BigFile.zip";
var ahref = $('<a>', { href:url } )[0]; // create an <a> element
var host = ahref.hostname.split('.').slice(1).join('.'); // example.com
You can have a regex to do this for you.
url = 'ftp://xxx:xxx#ftp.example.com/BigFile.zip'
base_address = url.match(/#.*\//)[0];
base_address = base_address.substring(1, base_address.length-1)
This would contain ftp.example.com though. You can fine tune it as per your need.
I just wanted to try/add something different (can't bet for performance or the general solution, but it works and hey ! without DOM/regexp involved):
var x="ftp://xxx:xxx#ftp.example.com/BigFile.zip"
console.log((x.split(".")[1]+ "." + x.split(".")[2]).split("/")[0]);
For the given case can be shortest since always will be ".com"
console.log(x.split(".")[1]+ ".com");
Another (messy) approach (and will work with .com.something:
console.log(x.substring((x.indexOf("#ftp"))+5,x.indexOf(x.split("/")[3])-1));
And well on this we're dependend about having "#ftp" and the slashes "/" (at least 3 of them or one after the .com.something) for example would not work with: ftp://xxx:xxx#ftp.example.com
Last update This will be my best
without DOM/RegExp, nicer (but also confusing) that the previous ones
solves the problem about having or don't the slashes,
still dependant on having "#ftp." in the string.
works with .com.something.whatever
(function (splittedString){
//this is a bit nicer, no regExp, no DOM, avoid abuse of "split"
//method over and over the same string
//check if we have a "/"
if(splittedString.indexOf("/")>=0){
//split one more time only to get what we want.
return (console.log(splittedString.split("/")[0]));
}
else{
return (console.log(splittedString));//else we have what we want
}
})(x.split("#ftp.")[1]);
As always it depends how maintainable you want your code to be, I just wanted to honor the affirmation about there's more than one way to code something. My answer for sure is not the best, but based on it you could improve your question.
So let's say there's a URL http://example.com/index.html/hello/hi where "hello" and "hi" are parameters.
How would you use javascript and forms method POST to extract the parameters?
Your subject is a little bit vague. However, I thought I'd made an example of possibilities.
http://jsfiddle.net/tive/LjbPq/
The idea is to split the URL for each character /, in whatever way you received it.
var parts = document.URL.split("/");
Since split() returns an array (zero based), you need to distract 1 from the total length to get the last index.
var lastPart = parts[parts.length - 1];
Run this in a for loop, and you should get the idea as occurring in the example.
documentation on document.URL to retreive the complete URL
documentation on window.location to use properties of a url (protocol, href, pathname, ...)
this could work...
var secondvar = window.location.href.split('/')[window.location.href.split('/').length];
var firstvar = window.location.href.split('/')[window.location.href.split('/').length-1];
I am able to get the querystring from url like this using regex and javascript: But I need to get rid of these %22...these don't show up in IE, just in FF..How do I do that? Ineeed everything after k=..but without %22..
<script type="text/javascript">document.write('<div class="DynamicSearchTitle">
Showing All Results For ' +
location.href.match(/\&k\=(.+)/)[1]+ ' Matches </div>');
</script>
URL
http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=%22Hospital%22%20OR%20%22Office%22
The URL is broken so I can't take a look at the whole code, but I think what you're looking for is the decodeURI-function.
decodeURI("%22")
for example would return "
Unescapeing the url from your question:
decodeURI("&k=%22Hospital%22%20OR%20%22Office%22");
returns &k="Hospital" OR "Office"
You can get all the Query String component by simple JS function described here
Use it like this,
var uparts = getUrlParts(location.href);
var the_K = uparts["k"];
I have a javascript object that I need to be able to pass to a web service via query string.
Say for example:
<script type="text/javascript">
var test = new Object();
test.date = new Date();
test.str = "hello world!";
test.list = new Array();
test.list.push('a');
test.list.push('b');
test.list.push('c');
</script>
Is there a way that I can serialize that object as JSON and then compress/encode it in some way that can be passed into a url's query string?
like:
var destination = 'http://mywebservice?'+encode(serialize(test));
$.get(destination, function(e)) { ... }
Thanks in advance
You want Douglas Crockford's json2.js: https://github.com/douglascrockford/JSON-js
var test = new Object();
test.date = new Date();
test.str = "hello world!";
var dest = 'http://mywebservice?'+encodeURIComponent( JSON.stringify(test) );
(oh, and don't use escape(), it's deprecated. Always use encodeURIComponent() instead)
But why not use a (session) cookie instead? Using the URI to pass data can be a major problem for SEO, for bookmarks, for links, etc.
You should remember that query string has maximum length (wiki said that it is 2083 chars), so you have to be carefully with putting there too large objects.
I think you just need jQuery post function:
http://api.jquery.com/jQuery.post/
It does perform a post of the data to the server. In my opinion a POST is better suited to send objects but I ignore the limitations you might have on the server.
Use the standard JSON stringify() method:
var destination = encodeURI('http://mywebservice?obj='+ JSON.stringify(test));