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

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')
)

Related

How do JSON.parse() and escape characters work in JavaScript?

Suppose I have an object variable:
var obj = {
key: '\"Hello World\"'
}
Then I tried parse it to string by using JSON.stringify in Chrome devtools console:
JSON.stringify(obj) // "{"key":"\"Hello World\""}"
I get the result "{"key":"\"Hello World\""}". Then I give it to a string
var str = '{"key":"\"Hello World\""}'
At least I try to convert it back to obj:
JSON.parse(str);
but the browser tell me wrong Uncaught SyntaxError
What confused me is why this is wrong? I get the string from an origin object and I just want turn it back.
How can I fix this problem? If I want do the job like convert obj to string and return it back, how can I do?
You're tried to convert your JSON into a string literal by wrapping it in ' characters, but \ characters have special meaning inside JavaScript string literals and \" gets converted to " by the JavaScript parser before it reaches the JSON parser.
You need to escape the \ characters too.
var str = '{"key":"\\"Hello World\\""}'
That said, in general, it is better to not try to embed JSON in JavaScript string literals only to parse them with JSON.parse in the first place. JSON syntax is a subset of JavaScript so you can use it directly.
var result = {"key":"\"Hello World\""};
try:
var str = '{"key":"\\"Hello World\\""}';

How to ignore escape characters in javascript?

I have the following string:
var str = '\x27';
I have no control on it, so I cannot write it as '\\x27' for example. Whenever I print it, i get:
'
since 27 is the apostrophe. When I call .length on it, it gives me 1. This is of course correct, but how can I treat it like a not escaped string and have it print literally
\x27
and give me a length of 4?
I'm not sure if you should do what you are trying to do, but this is how it works:
var s = '\x27';
var sEncoded = '\\x' + s.charCodeAt(0).toString(16);
s is a string that contains one character, the apostrophe. The character code as a hexadecimal number is 27.
After the assignment var str = '\x27';, you can't tell where the contents of str came from. There's no way to find out whether a string literal was assigned, or whether the string literal contained an escape sequence. All you have is a string containing a single apostrophe character (Unicode code point U+0027). The original assignment could have been
var str = '\x27'; // or
var str = "'"; // or
var str = String.fromCodePoint(3 * 13);
There's simply no way to tell.
That said, your question looks like an XY problem. Why are you trying to print \x27 in the first place?

Convert this unicode to string with javascript (Thai Language)

มอเตอร์ไซค์
Can I convert this unicode to string with JS. (It is Thailand Language)
I use
console.log(String.fromCharCode("มอเตอร์ไซค์"));
And It's not correct. if it right it will show มอเตอร์ไซค์
Your Unicode string is encoded using HTML entity notation. Generally that means that whatever encoded the string expected it to end up in the middle of an HTML document, where it would be seen by an HTML parser.
If you've somehow got that string in JavaScript in a browser, you can get to the encoded Unicode by letting the browser parse it:
var str = "มอเตอร์ไซค์";
var elem = document.createElement("div");
elem.innerHTML = str;
alert(elem.textContent);
The string.fromCharCode() function expects one or more numeric arguments; it won't understand HTML entities. Thus if you're not in a browser (like, if you've got the string in a Node.js program or something like that), you could convert the string with your own code:
var str = "มอเตอร์ไซค์";
var thai = String.fromCharCode.apply(String, str.match(/x[^;]*;/g).map(function(n) { return parseInt(n.slice(1, -1), 16); }));
That conversion will only work when the code points involved are within the first 64K values.
You may want something like this :
var input = "มอเตอร์ไซค์";
var output = input.replace(/&#x[0-9A-Fa-f]+;/g,
function(htmlCode) {
var codePoint = parseInt( htmlCode.slice(3, -1), 16 );
return String.fromCharCode( codePoint );
});

Escape Base64 String in URL?

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 )));
};

Parse string in javascript

How can I parse this string on a javascript,
var string = "http://www.facebook.com/photo.php?fbid=322916384419110&set=a.265956512115091.68575.100001022542275&type=1";
I just want to get the "265956512115091" on the string. I somehow parse this string but, still not enough to get what I wanted.
my code:
var newstring = string.match(/set=[^ ]+/)[0];
returns:
a.265956512115091.68575.100001022542275&type=1
try this :
var g=string.match(/set=[a-z]\.([^.]+)/);
g[1] will have the value
http://jsbin.com/anuhog/edit#source
You could use split() to modify your code like this:
var newstring = string.match(/set=[^ ]+/)[0].split(".")[1];
For a more generic approach to parsing query strings see:
Parse query string in JavaScript
Using the example illustrated there, you would do the following:
var newstring = getQueryVariable("set").split(".")[1];
You can use capturing group in the regex.
const str = 'http://www.facebook.com/photo.php?fbid=322916384419110&set=a.265956512115091.68575.100001022542275&type=1';
console.log(/&set=(.*)&/.exec(str)[1]);

Categories

Resources