I was reviewing some code and I saw something like this:
if (result.indexOf('?') === -1) {
result += '?';
}
result += '&' + SOMETHING;
Clearly this can result in an URL like this http://example.com?&a=b
The author of the code sees nothing unusual in the code but ?& bothers me. I could not find any restrictions in the RFC for URI to prove him wrong (or maybe I missed it).
Clearly in the network tab of Chrome dev tools it appears as an empty pair:
Should URL like this bother me or am i just paranoid?
This case will be interpreted as an empty value by most servers, so yes, it is indeed valid. What's going to happen is that the server checks between ? and every & and then separates the values at = accordingly.
So when there is nothing between a ? and a & (or two &'s), the values will both be empty. Missing ='s will affect whether the value is "" or null, but it will not make the query invalid.
Watch out with this, because some parsers might not find this to be valid, so you may get problems when using custom parsers (in JavaScript for example).
I wrote up a blog post about some of these edge cases years ago.
tl;dr: yes, ?&example is valid
What's important about it is that you're defining a key of "" with a value of null.
You can pretty much guarantee that almost no libraries support those empty string keys, so don't rely on them working, but as far as having a URL along the lines of ?&foo=bar, you should be fine when accessing the foo key.
Related
When developing React app should we check every property if exists to make sure our app does not crash? I currently have for ex something like below:
<h3>{block && block.box && block.box.title}</h3>
but I wonder if I should do it like this:
<h3>{block && block.box && block.box.title && block.box.title}</h3>
to make sure block.box.title exists before accessing it!
Any idea how can i handle these things in javascript in general, this approach seems kinda verbose to me.
UPDATE, should this check be enough:
<h3>{block.box.title && block.box.title}</h3>
In this example, I think it's safe to assume that block exists, otherwise your code is probally incorrectly written, so that check isn't needed.
Then, the double title makes no sense. The syntax you're using (and most people) is a bit of a cheat, it effectivly does this:
isset(block) && isset(block.box) && echo(block.box.title)===true
This makes use of the fact that a string is considered true and that javascript parses from left to right.
It evaluates/runs the 1st part: run the ISSET, continue the checks if that's true
It evaluates/runs the 2nd part: run the ISSET, continue the checks if that's true
...
It evaluates/runs the last part: Echo the output, continue the checks if it's true.
At the last point, it has already output the string, then it evaluates the outcome. If the string hasn't been output (it's empty or it doesnt exists) that will return false.
Response to your update: No that wont work. It will try to access the title property of null if box doesn't exist, which results in an error,
New js feature here:
<h3>{block?.box?.title}</h3>
I have the following javascript which works fine for the most part. It gets the user that has logged in to the site and returns their DOMAIN\username info. The problem arises when the username starts with a letter that completes a valid escape character (eg. DOMAIN\fname). The \f gets interpolated and all kinds of terrible things happen. I have tried every sort of workaround to try and replace and/or escape/encode the '\'. The problem is the \f does not seem like it is available to process/match against. The string that gets operated on is 'DOMAINname'
// DOMAIN\myusername - this works fine
// DOMAIN\fusername - fails
var userName='<%= Request.ServerVariables("LOGON_USER")%>';
userName = userName.replace('DOMAIN','');
alert("Username: " + userName);
I also see all kinds of weird behaviour if I try to do a workaround using the userName variable, I think this may be because it contains a hidden \f. I've searched high and low for a solution, can't find a thing. Tried to find out if I could remove the DOMAIN\ on the serverside but that doesn't seem available either. Does anyone have a solution or workaround? In the debugger, the initial value of the servervariable is correct but the next immediate call to that variable is wrong. So the interpolated values in the debugger look like this:
var userName='DOMAIN\fusername';
userName; // 'DOMAINusername' in debugger.
Thanks
If you're using ASP.net (as it looks like you are), use AjaxHelper.JavaScriptStringEncode or HttpUtility.JavaScriptStringEncode to output the string correctly.
var userName='<%= HttpUtility.JavaScriptStringEncode(Request.ServerVariables("LOGON_USER"))%>';
I have a very specific problem concerning a regular expression matching in Javascript. I'm trying to match a piece of source code, more specifically a portion here:
<TD WIDTH=100% ALIGN=right>World Boards | Olympa - Trade | <b>Bump when Yasir...</b></TD>
The part I'm trying to match is boardid=106121">Olympa - Trade</a>, the part I actually need is "Olympa". So I use the following line of JS code to get a match and have "Olympa" returned:
var world = document.documentElement.innerHTML.match('/boardid=[0-9]+">([A-Z][a-z]+)( - Trade){0,1}<\/a>/i')[1];
the ( - Trade) part is optional in my problem, hence the {0,1} in the regex.
There's also no easier way to narrow down the code by e.g. getElementsByTagName, so searching the complete source code is my only option.
Now here's the funny thing. I have used two online regex matchers (of which one was for JS-regex specifically) to test my regex against the complete source code. Both times, it had a match and returned "Olympa" exactly as it should have. However, when I have Chrome include the script on the actual page, it gives the following error:
Error in event handler for 'undefined': Cannot read property '1' of null TypeError: Cannot read property '1' of null
Obviously, the first part of my line returns "null" because it does not find a match, and taking [1] of "null" doesn't work.
I figured I might not be doing the match on the source code, but when I let the script output document.documentElement.innerHTML to the console, it outputs the complete source code.
I see no reason why this regex fails, so I must be overlooking something very silly. Does anyone else see the problem?
All help appreciated,
Kenneth
You're putting your regular expression inside a string. It should not be inside a string.
var world = document.documentElement.innerHTML.match(/boardid=[0-9]+">([A-Z][a-z]+)( - Trade){0,1}<\/a>/i)[1];
Another thing — it appears you have a document object, in which case all this HTML is already parsed for you, and you can take advantage of that instead of reinventing a fragile wheel.
var element = document.querySelector('a[href*="boardid="]');
var world = element.textContent;
(This assumes that you don't need <=IE8 support. If you do, there remains a better way, though.)
(P.S. ? is shorthand for {0,1}.)
I'm using document.location.hash to preserve state on the page, and I'm putting url-encoded key value pairs up there, separated by "&" chars. So far so good.
However I'm running into an annoying problem on Firefox -- Firefox will quietly url-decode the hash value on the way in, so when you get it out later it's been decoded.
I can patch the problem by detecting when I'm running on firefox and calling encodeURIComponent on everything twice on the way in, but obviously that is hideous and I don't really want to do that.
Here's a simple example, where I encode "=" as "%3D", put it in the hash, and when I get it out later it's been turned back into "=" automatically:
// on the way in::
document.location.hash = "foo=" + encodeURIComponent("noisy=input");
//then later.....
// on the way out:
var hash = document.location.hash;
kvPair = hash.split("=");
if (kvPair.length==2) {
console.log("that is correct.")
} else if (kvPair.length==3) {
console.log("oh hai firefox, this is incorrect")
}
I have my fingers crossed that there's maybe some hidden DOM element that firefox creates that represents the actual (un-decoded) hash value?
but bottom line -- has anyone run into this and found a better solution than just doing browser detection and calling encodeURIComponent twice on Firefox?
NOTE: several other questions I think have the same root cause. Most notably this one:
https://stackoverflow.com/questions/4834609/malformed-uri-in-firefox-not-ie-using-encodeuricomponenet-and-setting-hash
I would strongly advise against using the hash value to preserve the state. Hash is supposed to point to object's fragment-id, as explained in RFC 1630
This represents a part of, fragment of, or a sub-function within, an
object. (...) The fragment-id follows the URL of the whole object from which it is
separated by a hash sign (#).
Is there anything stopping you from using cookies to preserve the state? Cookies are simple enough to use in JS, described on Geko DOM Reference pages, and would do the trick quietly, without appending values to the URL which is never pretty.
If you absolutely have to use hash though, you may want to consider replacing '=' with some other character, e.g. ":".
What you could do, is change the "=" to something else using
var string = string2.replace("=", "[$equals]")
You may have to run the line above a couple of times, depending on how many "=" there are.
Then same process you had as above.
NB If you require it for further code, you can replace [$equals] back to "=" after splitting the hash into an array.
a quick, probably easy question whose answer is probably "best practice"
I'm following a tutorial for a custom-template mobile Safari webapp, and to change views around this code is used:
function btnSave_ClickHandler(event)
{
var views = document.getElementById('stackLayout');
var front = document.getElementById('mainScreen');
if (views && views.object && front) {
views.object.setCurrentView(front, true);
}
}
My question is just about the if conditional statement. What is this triplet saying, and why do each of those things need to be verified before the view can be changed? Does views.object just test to see if the views variable responds to the object method? Why is this important?
EDIT - This is/was the main point of this question, and it regards not Javascript as a language and how if loops work, but rather WHY these 3 things specifically need to be checked:
Under what scenarios might views and front not exist?
I don't typically write my code so redundantly. If the name of my MySQL table isn't changing, I'll just say UPDATE 'mytable' WHERE... instead of the much more verbose (and in my view, redundant)
$mytable = "TheSQLTableName";
if ($mytable == an actual table && $mytable exists && entries can be updated){
UPDATE $mytable;
}
Whereas if the table's name (or in the JS example, the view's names) ARE NOT "hard coded" but are instead a user input or otherwise mutable, I might right my code as the DashCode example has it. So tell me, can these values "go wrong" anyhow?
Thanks!
The if is testing those 3 pointers to make sure they are non-null. A null pointer is 0 which converts to false. If any of those 3 pointer are 0 (null) then it won't try to use them.
I'm not sure what dereferencing a null pointer does in Javascript but it's an error and may cause an exception. The if is just avoiding that possibility.