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 ;)
Related
I would like to extract the middle ID from below string
const url = "https://state.velon.com/11eb35c9-3c69-e7f2-a4eb-0ac9483cdf87/reports/corporate";
And I want to grab the middle ID = "11eb35c9-3c69-e7f2-a4eb-0ac9483cdf87" from the string
Should I just use substring and index of or are there other ways of doing that. Please help
Using the built-in URL api is probably the canonical way and the safest way to do it:
const urlString = "https://state.velon.com/11eb35c9-3c69-e7f2-a4eb-0ac9483cdf87/reports/corporate";
const url = new URL(urlString);
console.log(url.pathname.split("/")[1]);
URLs can get pretty crazy, so we should just rely on the built-in way to parse it for us :)
I have stumbled across this issue and hope I can get some inputs here on what could be the cause.
I have a URL with some GET parameters as follows:
www.test.com/test.jsp?serial=Id123:true;Id456:true;Id789:false;&session=1234567&userId=test
I then extract the parameter to make a REST call
const params = new URLSearchParams(window.location.search);
console.log(window.location.search);
console.log(params.get("serial"));
console.log(params.get("session"));
console.log(params.get("userId"));
const url = new URL("service/resources/query?", document.baseURI).href;
fetch(url + params.toString())
I'd say half of the time my REST call would fail due to session and userId parameters being cut off. Instead, I'm seeing this in my browser
www.test.com/test.jsp?serial=Id123:true
And my console print out would show
?serialNum=ZD0222:True
Id123:True
null
null
Any suggestions on why this happens and how I can write differently here?
Additional note - could the semicolon be the cause here? I noticed that url only show first value of the first parameter.
I think your window.location.search is not what you expect.
Looks good when I explicitly define the URL.
const url = new URL("http://www.test.com/test.jsp?serial=Id123:true;Id456:true;Id789:false;&session=1234567&userId=test");
const params = new URLSearchParams(url.search);
console.log(url.search);
console.log(params.get("serialNum"));
console.log(params.get("sessionId"));
console.log(params.get("userId"));
I would take another direction, maybe something like
const url = 'http://www.test.com/test.jsp?serial=Id123:true;Id456:true;Id789:false;&session=1234567&userId=test',
matches = url.match(/([&?](\w*)=([^?&]*))/g),
res = matches.reduce((acc, el)=> {
const sub = el.match(/[&?](.*)=(.*)/)
acc[sub[1]] = sub[2]
return acc
}, {})
console.log(res)
Please note: that function is not dealing with many edge cases, but maybe can inspire You to find an acceptable way to get what You need.
You cannot have colon ( : ) in your URL, its considered as an invalid character. You can use colon only in special cases like specifying port number or in 'http://', etc.
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.
I want to remove the string code=hads1328fas& on my URL, so that
BEFORE
http://example.com/main/index.php?code=hads1328fas&store=food#home
AFTER
http://example.com/main/index.php?store=food#home
However, the string code=hads1328fas& may not always the same, so the code below won't works in this case.
var url = window.location.href;
url.replace('code=hads1328fas&')
Is there any way that is possible for the case?
Thanks
Use regular expressions:
url = "http://example.com/main/index.php?code=hads1328fas&store=food#home";
url = url.replace(/code=[^&]+&/,'');
After this, url will contain
http://example.com/main/index.php?store=food#home
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'));