Advanced Find and Replace Based off What is Found - Javascript - javascript

I am trying to simplify a process with a script. What is happening is I have a decent size script that has lots of base-64 encoded strings, and I would like to replace them with the decoded version (using atob and btoa). For example, I have atob("MHhfZXhwb3J0") and would like to replace it with the output of atob("MHhfZXhwb3J0"), which is "0x_export". I have tried splitting the code for atob(", then saving the contents and replacing them, but for some reason it breaks at some point. I have tried using string.replace(/*/g, *), but it seems that you cannot use functions in replace. I am sorry if I am not the best at describing my question, so if anyone has further question, I would be glad to reply.
A small example of what I am trying to do is shown below:
The beginning example script:
function test(callback, number, reason) {
if (number != atob("MA==")) {
console.log(atob("RmFpbGVkOiA=") + reason + atob("LiBQbGVhc2UgdHJ5IGFnYWluLg=="));
} else {
callback(number);
}
}
The afterwards example script:
function test(number, reason) {
if (number != "0") {
console.log("Failed: " + reason + ". Please try again.");
} else {
callback(number);
}
}

You can pass functions to replace - you can paste the whole code into some Javascript editor as a string, and then replace every instance of atob("...") with the decoded text:
const inputScript = `
function test(callback, number, reason) {
if (number != atob("MA==")) {
console.log(atob("RmFpbGVkOiA=") + reason + atob("LiBQbGVhc2UgdHJ5IGFnYWluLg=="));
} else {
callback(number);
}
}
`;
const outputScript = inputScript
.replace(/atob\("([^\"]+)"\)/g, (_, p1) => `"${atob(p1)}"`)
.trim();
console.log(outputScript);

Related

javascript is there a way to clean up a string multiple times in a clean way

I'm trying to clean up a JSON string (that was converted from a json object) and I found that many people use the .replace() method to do so. However, in doing so my code looked like this:
scrape(url).then(result => {
final = JSON.stringify(result);
final = final.replace(/['"]+/g, "");
final = final.replace(/[{]+/g, "");
final = final.replace(/[}]+/g, "");
final = final.replace(/[:]+/g, ": ");
final = final.replace(/,+/g, ";");
return final;
});
While this method does work returning 'final' in the way i want it, it does not seem very efficient and the code is really clunky. My end goal is to remove quotes, curly brackets, replace ':' with ': ' and change all commas to semi colons. Is there a better/cleaner way to do this?
EDIT:
The input string looks something like this:
{
'$primary': '#ea80fc',
'$p_light': '#ffb2ff',
'$p_dark': '#b64fc8',
'$secondary': '#b64fc8',
'$s_light': '#f9683a',
'$s_dark': '#870000'
}
Given your actual data, where after JSON.parse you have the following structure:
{
'$primary': '#ea80fc',
'$p_light': '#ffb2ff',
'$p_dark': '#b64fc8',
'$secondary': '#b64fc8',
'$s_light': '#f9683a',
'$s_dark': '#870000'
}
turning this into legal SCSS doesn't require a long chain of replaces applied to the JSON string at all. It just requires parsing the JSON to plain JS object, and then iterating over the key/values to form an SCSS string:
function jsonToSCSS(stringdata=``, data={}) {
/* JSON.parse can throw. Always be ready for that. */
try { data = JSON.parse(stringdata); }
catch (e) { console.warn(e); return ``; }
return Object.keys(data)
.map(key => `${key}: ${data[key]};`)
.join('\n');
}
And done. The output of that function is now a normal, formatted string:
$primary: #ea80fc;
$p_light: #ffb2ff;
$p_dark: #b64fc8;
$secondary: #b64fc8;
$s_light: #f9683a;
$s_dark: #870000;
Which you can now write into whatever file you need it written into, either directly, or itself wrapped in formatting:
const SCSS = jsonToSCSS(inputdata);
const qualified = `.someclass { ${SCSS} }`;
More simplified
scrape(url).then(result => {
return JSON.stringify(result.replace(/['"{}]+/g, "").replace(/[:]+/g, ":").replace(/,+/g, ";"));
});

Force percent-encode in JS

How can I percent-encode a string like "ü" such that it comes out as "%C3%BC"?
Here's my current implementation:
function percentEncode(ch) {
return '%' + ch.codePointAt(0).toString(16).toUpperCase().padStart(2,'0');
}
But that encodes it as '%FC'.
encodeURIComponent handles it correctly, but I need to encode some characters which encodeURIComponent refuses to encode, so I can't use that.
I think I figured it out.
const UTF8_ENCODER = new TextEncoder();
function percentEncode(str) {
return Array.from(UTF8_ENCODER.encode(str)).map(i => '%' + i.toString(16).toUpperCase().padStart(2,'0')).join('');
}
console.log(percentEncode('ü'))
credit

Replace accented characters with their unaccented equivalent

I have a text field that can not allow accents. I was using this code:
<input type="text" onkeyup="value=value.replace(/[^0-9a-zA-Z' ']/g,'')">
But rather than blocking the characters, I need them to be replaced for example by typing Ç change to C
I found a function and hes working, but when I type a dot appears the letter A
Can you help me?
<script>function retiraAcento(palavra,obj){
com_acento = 'áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ<,>´`-,*/~';
sem_acento = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC ';
nova='';
for(i=0;i<palavra.length;i++) {
if (com_acento.search(palavra.substr(i,1))>=0) {
nova+=sem_acento.substr(com_acento.search(palavra.substr(i,1)),1);
} else {
nova+=palavra.substr(i,1);
}
}
obj.value = nova;}</script><input type="text" onKeyUp="javascript:retiraAcento(this.value, this);">
I didn't dig into it enough to see why the . was being replaced with A, but this version doesn't have that behaviour. It doesn't work exactly the same and it operates on the whole string, but that likely isn't a problem unless it's used in a large textfield, in which case it could be optimised other ways.
const com_acento = 'áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ<,>´`-,~';
const sem_acento = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC ';
function retiraAcento(string) {
return string
.split('')
.map(char => {
const charIdx = com_acento.indexOf(char)
if (charIdx !== -1) {
return sem_acento[charIdx]
}
return char
})
.join('')
}
function replaceCharOnChange(evt) {
event.target.value = retiraAcento(evt.target.value)
}
document.querySelector('input').addEventListener('keyup', replaceCharOnChange)
Apologies it's half rewritten in english! I'd also look into using another data structure than the two same-length strings. The simplest would be an object lookup table eg:
{á: 'a', ç: 'c', ...}
but there's other ways you could go about it too

regexp looping and logic in javascript

Not certain if this can be done in regexp under javascript, but thought it would be interesting to see if it is possible.
So thought I would clean up a piece of html to remove most tags, literally just dropping them, so <H1><img><a href ....>. And that would be relatively simple (well, stole the basis from another post, thanks karim79 Remove HTML Tags in Javascript with Regex).
function(inString, maxlength, callback){
console.log("Sting is " + inString)
console.log("Its " + inString.length)
var regex = /(<([^>]+)>)/ig
var outString = inString.replace(regex, "");
console.log("No HTML sting " + outString);
if ( outString.length < maxlength){
callback(outString)
} else {
console.log("Lets cut first bit")
}
}
But then I started thinking, is there a way where I can control regex execution. So lets say that I want to keep certain tabs, like b,br,i and maybe change H1-6 to b. So in pseudo code, something like:
for ( var i in inString.regex.hits ) {
if ( hits[i] == H1 ) {
hits[i] = b;
}
}
The issue is that I want the text thats not HTML tags to stay as it is, and I want it to just cut out by default. One option would of course be to change the ones I want to keep. Say change <b> to [[b]], once that is done to all the ones of interest. Then put them back to <b> once all unknown have been removed. So like this (only for b, and not certain the code below would work):
function(inString, maxlength, callback){
console.log("Sting is " + inString)
console.log("Its " + inString.length)
var regex-remHTML = /(<([^>]+)>)/ig
var regex-hideB = /(<b>)/ig
var regex-showB = /([b])/ig
var outString = inString.replace(regex-hideB, "[b]");
outString = outString.replace(regex-remHTML, "");
outString = outString.replace(regex-showB, "<b>");
console.log("No HTML sting " + outString);
if ( outString.length < maxlength){
callback(outString)
} else {
console.log("Lets cut first bit")
}
}
But would it be possible to be smarter, writing cod ethat says here is a peice of HTML tag, run this code against the match.
As Tim Biegeleisen sai in its comment, maybe a better solution could be using a parser instead of a Regex...
By the way, if you want to control what is going to be changed by the regex you can pass a callback to the String.prototype.replace:
var input = "<div><h1>CIAO Bello</h1></div>";
var output = input.replace(/(<([^>]+)>)/gi, (val) => {
if(val.indexOf("div") > -1) {
return "";
}
return val;
})
;
console.log("output", output);

Javascript converting ' to URL language

I have a very simple JavaScript function that works totally fine, until one of the variables has a ' in it. This is what I tried:
function search(champ1,champ2,role) {
if((champ1!='')&&(champ2!='')){
if((champ1!=champ2)) {
var champ1_name = encodeURI(champ1);
var champ2_name = encodeURI(champ2);
var role_name = encodeURI(role);
window.location.href="http://myurl.com/"+role_name+"/"+champ1_name+"&"+champ2_name;
return false;
} else if(champ1==champ2) {
window.location.href="http://myurl.com/"+role;
}
}
}
but unfortunately when I run this script the URL still has the ' in it even after they ran through encodeURI()
If you need to escape ', do something like .replace("'", "%27"). Or use a URL escaping function that lets you provide a string of characters that need to be escaped.
decodeURIComponent("%27") converts back to "'".

Categories

Resources