TypeScript
by Vikram Deshmukh
HTML
<textarea id="input" column="10"></textarea>
<div id="container">
<button id="btnEncode">
Encode
</button>
<button id="btnDecode">
Decode
</button>
</div>
<textarea id="output" column="10"></textarea>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
textarea {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
text-align: center;
width: calc(100% - 40px);
height: 30vh;
text-align: left;
}
#container {
display: flex;
align-items: center;
justify-content: center;
}
TypeScript
const ESCAPE_CHARS = '+ - ! ( ) & # [ ] ^ ~ * :'.split(' ');
function encodeQueryParts (str: string) {
const label = str.substring(0, str.indexOf(':'));
let value = str.substring(str.indexOf(':') + 1);
if (label.substring(label.length - 2) === '_s') {
ESCAPE_CHARS.forEach(char => {
value = value.split(char).join('\\'+char);
})
console.log('escaped', value)
}
return label+':'+value;
}
function encodeQuery(str: string) {
str = str.split(' ').map(d=> {
return (d.indexOf(':') === -1 ? d : encodeQueryParts(d))
}).join(' ');
return window.btoa(str);
}
function decodeQuery (str: string) {
str = window.atob(str);
console.log(str)
str = str.split(' ').map(d=> {
return (d.indexOf(':') === -1 ? d : decodeQueryParts(d))
}).join(' ');
return str;
}
function decodeQueryParts (str: string) {
const label = str.substring(0, str.indexOf(':'));
let value = str.substring(str.indexOf(':') + 1);
if (label.substring(label.length - 2) === '_s') {
//value = window.btoa(value);
value = value.split('\\').join('');
}
return label+':'+value;
}
function decode() {
const input = document.querySelector("#output").value
document.querySelector("#input").value = decodeQuery(input);
}
function encode() {
const input = document.querySelector("#input").value
document.querySelector("#output").value = encodeQuery(input);
}
document.querySelector("#btnEncode").addEventListener('click', encode);
document.querySelector("#btnDecode").addEventListener('click', decode);