Escape Base64 String in URL? - javascript

For some reason I need to put a Base64 encoded string in the URL, i.e.
<script>
var URL = "localhost:8080/MyApp/order?z=AAAAAAAEJs4"
</script>
The URL is generated by Java, problem here is I can only use java to make the Base 64 encoded string to be URL friendly, but not javascript friendly, so fire bug give me the following error:
SyntaxError: unterminated string literal
Apparently there are charactors in the Base64 string requires escaping. However I cannot use escape() or URLencoding() method as the request will directly deliver to the controller and manipulated by java code, so there is no "next page" in this situation.
So how to make this work then?

If your're trying to convert that z url attribute into an understandable string/variable, you have to use a library to convert that. Below is a link to a base64 library for Javascript that you must load in.
http://www.webtoolkit.info/javascript-base64.html
You maybe also need a library to access the z attribute in your url. I would recommend this:
https://github.com/allmarkedup/purl

Just in case it helps, here is a short JS code requiring no dependency:
String.prototype.base64EncodeUrl = function () {
var str = this;
str = window.btoa(unescape(encodeURIComponent( str )));
return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
};
String.prototype.base64DecodeUrl = function () {
var str = this, str_pad = (str + '===');
str = str_pad.slice(0, str.length + (str.length % 4));
str = str.replace(/-/g, '+').replace(/_/g, '/');
return decodeURIComponent(escape(window.atob( str )));
};

Related

How to convert string from ENV to hex in JavaScript? [duplicate]

I have a string in JS in this format:
http\x3a\x2f\x2fwww.url.com
How can I get the decoded string out of this? I tried unescape(), string.decode but it doesn't decode this. If I display that encoded string in the browser it looks fine (http://www.url.com), but I want to manipulate this string before displaying it.
Thanks.
You could write your own replacement method:
String.prototype.decodeEscapeSequence = function() {
return this.replace(/\\x([0-9A-Fa-f]{2})/g, function() {
return String.fromCharCode(parseInt(arguments[1], 16));
});
};
"http\\x3a\\x2f\\x2fwww.example.com".decodeEscapeSequence()
There is nothing to decode here. \xNN is an escape character in JavaScript that denotes the character with code NN. An escape character is simply a way of specifying a string - when it is parsed, it is already "decoded", which is why it displays fine in the browser.
When you do:
var str = 'http\x3a\x2f\x2fwww.url.com';
it is internally stored as http://www.url.com. You can manipulate this directly.
If you already have:
var encodedString = "http\x3a\x2f\x2fwww.url.com";
Then decoding the string manually is unnecessary. The JavaScript interpreter would already be decoding the escape sequences for you, and in fact double-unescaping can cause your script to not work properly with some strings. If, in contrast, you have:
var encodedString = "http\\x3a\\x2f\\x2fwww.url.com";
Those backslashes would be considered escaped (therefore the hex escape sequences remain unencoded), so keep reading.
Easiest way in that case is to use the eval function, which runs its argument as JavaScript code and returns the result:
var decodedString = eval('"' + encodedString + '"');
This works because \x3a is a valid JavaScript string escape code. However, don't do it this way if the string does not come from your server; if so, you would be creating a new security weakness because eval can be used to execute arbitrary JavaScript code.
A better (but less concise) approach would be to use JavaScript's string replace method to create valid JSON, then use the browser's JSON parser to decode the resulting string:
var decodedString = JSON.parse('"' + encodedString.replace(/([^\\]|^)\\x/g, '$1\\u00') + '"');
// or using jQuery
var decodedString = $.parseJSON('"' + encodedString.replace(/([^\\]|^)\\x/g, '$1\\u00') + '"');
You don't need to decode it. You can manipulate it safely as it is:
var str = "http\x3a\x2f\x2fwww.url.com";
​alert(str.charAt(4)); // :
alert("\x3a" === ":"); // true
alert(str.slice(0,7))​; // http://
maybe this helps: http://cass-hacks.com/articles/code/js_url_encode_decode/
function URLDecode (encodedString) {
var output = encodedString;
var binVal, thisString;
var myregexp = /(%[^%]{2})/;
while ((match = myregexp.exec(output)) != null
&& match.length > 1
&& match[1] != '') {
binVal = parseInt(match[1].substr(1),16);
thisString = String.fromCharCode(binVal);
output = output.replace(match[1], thisString);
}
return output;
}
2019
You can use decodeURI or decodeURIComponent and not unescape.
console.log(
decodeURI('http\x3a\x2f\x2fwww.url.com')
)

How to replace / except in http://

I have a string and I need to replace %2f with /, except in http://.
Example:
var str = "http://locahost%2f";
str = str.replace(/%2f/g, "/");
Somehow I got str to output http:/locahost/.
Thanks in advance!
What should be used
You should use decodeURIComponent or decodeURI functions to decode encoded strings like yours. For example, decodeURIComponent("http://locahost%2f") will return http://localhost/.
That being said, decodeURIComponent should be used to decode components of a URI and not a full URI like http://locahost/.
You should look at this answer, it explains what is the difference between decodeURIComponent and decodeURI and when each should be used.
A workaround
As the first / are not encoded, it makes it difficult to find a Javascript functions doing exactly what you want. A working solution to decode your %2f after http:// would be to use String.prototype.split.
Working example:
var encoded = "http://localhost%2f";
var encodedArray = str.split("://");
var decoded = encodedArray[0] + "://" + encodedArray[1].replace(/%2f/g, "/");
This should work:
str = str.replace("%2f", "/");

How do you safely encode a URL using JavaScript?

specially * and ! characters which are not encoded using encodeUriComponent
As I've said in the comments, you don't have to encode * or ! in a query string. This is perfectly fine, for instance: http://example.com?foo=bar*!
You seem intent on doing it anyway. You can, if you want, but you don't have to.
Here's how you would if it were necessary:
var param = "bar*!";
param = encodeURIComponent(param)
.replace(/\*/g, '%2a') // 2a is the %-encoding of *
.replace(/!/g, '%21'); // 21 is the %-encoding of !
var url = "http://example.com?foo=" + param;
(If you need to unnecessarily encode other characters, you can get the %-encoding value for them like this: "*".charCodeAt(0).toString(16).)
Or actually, we can automate that:
var param = "bar*!";
param = encodeURIComponent(param).replace(/[*!]/g, function(m) {
return "%" + m.charCodeAt(0).toString(16);
});
var url = "http://example.com?foo=" + param;
...just add any others within the character class (the [...] in the regular expression). (This is less efficient, but it's unlikely to matter.)
But if whatever you're passing this parameter to fails with a raw * or !, I would expect it to fail with an encoded one as well.

How to display special html characters properly via javascript

I'm using javascript to get some asp.net server variables to display them, problem is that if the have some html special character the string isn't being assigned as it's on server and it displays wrong.
For example the string :
`ALBERTO GÓMEZ SÁNCHEZ`
is displaying like
`ALBERTO GóMEZ SáNCHEZ`
I know I could use a Replace function but doing that for every possible special html character seems too time consuming... I guess there must be some built-in function that solves that easily but I cannot find it or an easier method than trying to replace every possible html special character.
Do you know any way? Thanks for your help.
If you want to decode html string use this way:
function decodeHTMLEntities (str) {
if(str && typeof str === 'string') {
// strip script/html tags
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
}
return str;
}
Taken from here: HTML Entity Decode
If you want do put this html string into your DOM, you don't need to decode it, the browser will do this job for you.
Just insert it like this:
$("body").html(encodedHtmlStringFromServer);

Simple Regex question

I want to remove this from a url string
http://.....?page=1
I know this doesn't work, but I was wondering how you would do this properly.
document.URL.replace("?page=[0-9]", "")
Thanks
It seems like you want to get rid of the protocol and the querystring. So how about just concatenating the remaining parts?
var loc = window.location;
var str = loc.host + loc.pathname + loc.hash;
http://jsfiddle.net/9Ng3Z/
I'm not entirely certain what the requirements are, but this fairly simple regex works.
loc.replace(/https?\:\/\/([^?]+)(\?|$)/,'$1');
It may be a naive implementation, but give it a try and see if it fits your need.
http://jsfiddle.net/9Ng3Z/1/
? is a regex special character. You need to escape it for a literal ?. Also use regular expression literals.
document.URL.replace(/\?page=[0-9]/, "")
The answer from #patrick dw is most practical but if you're really curious about a regular expression solution then here is what I would do:
var trimUrl = function(s) {
var r=/^http:\/\/(.*?)\?page=\d+.*$/, m=(""+s).match(r);
return (m) ? m[1] : s;
}
trimUrl('http://foo.com/?page=123'); // => "foo.com/"
trimUrl('http://foo.com:8080/bar/?page=123'); // => "foo.com:8080/bar/"
trimUrl('foobar'); // => "foobar"
You're super close. To grab the URL use location.href and make sure to escape the question mark.
var URL = location.href.replace("\?page=[0-9]", "");
location.href = URL; // and redirect if that's what you intend to do
You can also strip all query string parameters:
var URL = location.href.replace("\?.*", "");

Categories

Resources