JavaScript, advanced .replace() - javascript

function changeText(getString){
var smiles_from_to = new Array();
smiles_from_to[":)"] = "ab"; smiles_from_to[":-)"] = "ab";
smiles_from_to[":("] = "ac"; smiles_from_to[":-("] = "ac";
smiles_from_to["B)"] = "af"; smiles_from_to["B-)"] = "af";
smiles_from_to[";("] = "crygirl2"; smiles_from_to[";-("] = "crygirl2";
smiles_from_to[":-*"] = "aw"; smiles_from_to[":*"] = "aw";
smiles_from_to[":D"] = "ag"; smiles_from_to[":-D"] = "ag";
smiles_from_to["(devil)"] = "aq"; smiles_from_to["(wtf)"] = "ai";
smiles_from_to["(sos)"] = "bc"; smiles_from_to["(boom)"] = "bb";
smiles_from_to["(rofl)"] = "bj"; smiles_from_to["xD"] = "bj";
smiles_from_to["(music)"] = "ar"; smiles_from_to["(angel)"] = "aa";
smiles_from_to["(beer)"] = "az"; smiles_from_to["(omg)"] = "bu";
smiles_from_to["(dance)"] = "bo"; smiles_from_to["(idiot)"] = "bm";
smiles_from_to["(clap)"] = "bi"; smiles_from_to["(gotkiss)"] = "as";
var replaced = getString;
for(var key in smiles_from_to){
replaced = replaced.replace(key, "<img src='"+chrome.extension.getURL("images/"+smiles_from_to[key]+".gif")+"' />");
}
return replaced;
}
Hi everyone ,I need to optimize code for something more simple, so try to avoid for loop..
"var replaced" is a huge html code (content of div that contains 100 lines of messages with date, username, userinfo(tooltip), message,.....)
This code is a piece from my chrome extension. so i cant do it php side.

You can use a single giant regex, of the form /:\)|:\(|.../g, then pass a callbacka as the replacement that looks up the match in your lookup object.

Related

How to split Javascript code (bs4) using Python

So I have been having some issues when trying to scrape Javascript values from a bs4 code.
Basically the javascript looks like
<script type="text/javascript">
var FancyboxI18nClose = 'Close';
var FancyboxI18nNext = 'Next';
var FancyboxI18nPrev = 'Previous';
var PS_CATALOG_MODE = false;
var ajaxsearch = true;
var attribute_anchor_separator = '-';
var blocksearch_type = 'top';
var combinationsFromController = {"163972":{"attributes_values":{"15":"40"},"attributes":[75],"price":0,"specific_price":false,"ecotax":0,"weight":0.6,"quantity":1,"reference":"IDP20059--IDPA163972","unit_impact":0,"minimal_quantity":"1","date_formatted":"","available_date":"","id_image":-1,"list":"'75'"}};
var comparator_max_item = 0;
</script>
and what I am trying to do here is to scrape the value var combinationsFromController = however what I tried to do is:
bs4 = soup(requests.text, 'html.parser')
for nosto_sku_tag in bs4.find_all('script', {'type': 'text/javascript'}):
if 'combinationsFromController' in nosto_sku_tag.text.strip():
print(nosto_sku_tag)
for att, values in json.loads(
re.findall('var combinationsFromController = (\{.*}?);', nosto_sku_tag.text.strip())[0][:-1]).values():
print(values)
Which gives me an error of Expecting ',' delimiter: line 1 column 4112 (char 4111)
I did realized that whenever I try to do
for nosto_sku_tag in bs4.find_all('script', {'type': 'text/javascript'}):
if 'combinationsFromController' in nosto_sku_tag.text.strip():
print(nosto_sku_tag)
print("---------")
The outprint gives me:
var FancyboxI18nClose = 'Close';
var FancyboxI18nNext = 'Next';
var FancyboxI18nPrev = 'Previous';
var PS_CATALOG_MODE = false;
var ajaxsearch = true;
var attribute_anchor_separator = '-';
var blocksearch_type = 'top';
var combinationsFromController = {"163972":{"attributes_values":{"15":"40"},"attributes":[75],"price":0,"specific_price":false,"ecotax":0,"weight":0.6,"quantity":1,"reference":"IDP20059--IDPA163972","unit_impact":0,"minimal_quantity":"1","date_formatted":"","available_date":"","id_image":-1,"list":"'75'"}};
var comparator_max_item = 0;
----------------------------
Which seems to mean that the javascript code is as one code which I believe maybe needs to split, However I tried to use regex for it but it didn't help me.
So my question is how am I able to scrape ONLY the value var combinationsFromController =?
Use the following regex pattern to isolate the entire javascript object which is assigned to that variable.
combinationsFromController = (.*?);
Try it here.
E.g.
import requests, re, json
r = requests.get(url)
p = re.compile(r'combinationsFromController = (.*?);', re.DOTALL)
data = json.loads(p.findall(r.text)[0])

Is there a way to condense this into fewer lines? HTML

My code that I'd like to condense:
document.getElementById("costA").innerHTML = currentCost[0];
document.getElementById("costB").innerHTML = currentCost[1];
document.getElementById("costC").innerHTML = currentCost[2];
document.getElementById("costD").innerHTML = currentCost[3];
document.getElementById("costE").innerHTML = currentCost[4];
document.getElementById("costF").innerHTML = currentCost[5];
document.getElementById("costG").innerHTML = currentCost[6];
document.getElementById("costH").innerHTML = currentCost[7];
document.getElementById("amountA").innerHTML = building[0];
document.getElementById("amountB").innerHTML = building[1];
document.getElementById("amountC").innerHTML = building[2];
document.getElementById("amountD").innerHTML = building[3];
document.getElementById("amountE").innerHTML = building[4];
document.getElementById("amountF").innerHTML = building[5];
document.getElementById("amountG").innerHTML = building[6];
document.getElementById("amountH").innerHTML = building[7];
document.getElementById("bonusA").innerHTML = currentBonuses[0];
document.getElementById("bonusB").innerHTML = currentBonuses[1];
document.getElementById("bonusC").innerHTML = currentBonuses[2];
document.getElementById("bonusD").innerHTML = currentBonuses[3];
document.getElementById("bonusE").innerHTML = currentBonuses[4];
document.getElementById("bonusF").innerHTML = currentBonuses[5];
document.getElementById("bonusG").innerHTML = currentBonuses[6];
document.getElementById("bonusH").innerHTML = currentBonuses[7];
I see three main sections that look like they can be condensed. I'd also, perhaps, prefer a way to be able to add or subtract an arbitrary number of buildings without changing too much of the code.
You can update in a loop. Following is a very basic representation:
var alphabetArr = ["A", "B","C","D","E","F","G","H"];
alphabetArr.forEach(function(row, i){
document.getElementById("cost" + row).innerHTML = currentCost[i];
document.getElementById("amount" + row).innerHTML = building[i];
document.getElementById("bonus" + row).innerHTML = currentBonuses[i];
})
Just in case, here is another way to do it without hard coding an array of letters. Another benefit is that this avoids Array.prototype.forEach which is not available in Internet Explorer 8
var start = "A".charCodeAt(0);
var end = "H".charCodeAt(0);
for (var i = start; i <= end; i += 1) {
var row = String.fromCharCode(i);
document.getElementById('cost' + row).innerHTML = currentCost[i - start];
document.getElementById('amount' + row).innerHTML = building[i - start];
document.getElementById('bonus' + row).innerHTML = currentBonuses[i - start];
}

Having trouble with image preload code

I have this object constructor function that has a preload method for preloading
rollover images pairs.
So, I have two questions:
1: why is the alert dialog just doing 'STR: ' with no data attached? (this type of problem is generally due to my blindness.
2: is it possible to treat the this.buttons_on and this.buttons_off as objects in that instead of
a numerical index, use a sting index so the rollover event handler does not need to loop through
the buttons_on and buttons_off arrays to get the one that should be swapped out;
function _NAV()
{
this.list_off = [];
this.list_on = [];
this.buttons_on = [];
this.buttons_off = [];
this.buttons_all = {}; // .on and .off
this.button_events = {};
this.img = true;
this.img_ids = {}
this.preLoad = function()
{
if(document.images) //creates image object array for preload.
{
var STR = '';
for(var i = 0; i < list_off.length; i++)
{
var lab_on = list_on[i].replace('\.jpg', '');
var lab_off = list_off[i].replace('\.jpg', '');
STR += lab_on+'||'+lab_off+"\n";
this.buttons_on[i] = new Image();
this.buttons_on[i].src = srcPath+list_on[i];
this.bottons_on[i].id = img_ids[i];
this.buttons_off[i] = new Image();
this.buttons_off[i].src = srcPath+list_off[i];
this.buttons_off[i].id = img_ids[i];
}
alert("STR: "+STR);
}
else
{
this.img = false
}
}
//// ...etc...
Here is the call before the onload event fires
var rollover = new _NAV();
rollover.preLoad();
Here are the arrays used
var srcPath = '../nav_buttons/';
var list_off = new Array(); // not new Object;
list_off[0] = "bio_off.jpg";
list_off[1] = "cd_off.jpg";
list_off[2] = "home_off.jpg";
list_off[3] = "inst_off.jpg";
list_off[4] = "photo_off.jpg";
list_off[5] = "rev_off.jpg";
list_off[6] = "samp_off.jpg";
var list_on = new Array();
list_on[0] = "bio_on.jpg";
list_on[1] = "cd_on.jpg";
list_on[2] = "home_on.jpg";
list_on[3] = "inst_on.jpg";
list_on[4] = "photo_on.jpg";
list_on[5] = "rev_on.jpg";
list_on[6] = "samp_on.jpg";
var img_ids = new Array();
Thanks for time and attention.
1:
Try PHPGlue's suggestion and add this. in front of all your member variables (this.list_on, this.list_off, this.img_ids)
You also have a typo on one line. bottons_on is misspelled.
this.bottons_on[i].id = img_ids[i];
2:
Yes, you can use a string as an index. Just make buttons_on and buttons_off objects instead of arrays.
function _NAV()
{
this.buttons_on = {};
this.buttons_off = {};
// For example:
this.buttons_off[lab_off] = new Image();
}

how to retrieve object from sqLite query? having problems

I am querying a local database and trying to retrieve my data in a form of array of objects to be able to manipulate them in another stage.
Below is my code and the scope I can access my object in and where I fail to access the object.
function setStageOneup(){
var teams = localStorage.teamsUp;
var tournament_id = 1;
var statement = "SELECT * FROM teams WHERE t_id= '"+tournament_id+"';";
localStorage.teamsUp = "";
var team_array = {};
var myTest = callBack(function(val){
var team = {};
for(var i = 0; i < val.rows.length; i++)
{
// teams_array[i]['id'] = val.rows.item(i).id
//console.log(val.rows.item(i).text)
team.id = val.rows.item(i).id;
team.t_id = val.rows.item(i).t_id;
team.m_t_id = val.rows.item(i).m_t_id;
team.name = val.rows.item(i).name;
team.weight = val.rows.item(i).weight;
team.goals = val.rows.item(i).goals;
team.win = val.rows.item(i).win;
team.draw = val.rows.item(i).draw;
team.lost = val.rows.item(i).lost;
team.misc = val.rows.item(i).misc;
team_array[i] = team;
console.log(team); // I am able to hee the output here
}
console.log(team_array); // I am able to hee the output here
},statement);
console.log(team_array); // I am unable to see here even though the variable is decleared in this scope
}
Thank you, if I missed anything please let me know.

certain global(class) variables disappearing in javascript? (photoshop)

I'm working on a plug-in script for photoshop and I'm encountering a really weird problem, the closest person to have this problem is here : Why do class variables in Javascript disappear when trying to call them multiple times or assigning them to local variables?
So reading his solution I combed over my syntax and I can't find any issues that I didn't correct and try again. I'll include the full code in a bit but here is the gist of the problem, I'm declaring this object in global space by declaring it and it's members outside of functions:
prefs = new Object();
prefs.db_file = "";
prefs.bk_file = "";
prefs.text = new Object();
prefs.text.top = 0.6;
prefs.text.bottom = 0.9;
prefs.text.padding = 0.05;
prefs.text.size = 12;
prefs.text.shadow = true;
basic outline (pseudocode):
declare global variables
main() {
Dialogue()
do stuff with the variables
}
Dialogue() {
declare new window
accept user interaction
store in global variable
}
I've run through this several times, step by step in the extendscript debugger watching the variables, every time the variables exist and the values are correct, until they exit the Dialogue() function then the only variables that exist are prefs.text.shadow and prefs.text.size
everything I've tried, including removing the ".text." part has returned the same. I can't find if my syntax is wrong, if it is wrong than why don't all the prefs. variables disappear? and I'm fairly certain that all the variables are treated the same way.
Update 10-22-2013: To help rule out syntax issues I found JSlint and ran my code through it and went through and corrected the issues it presented. The only issues left are grouping 'var' selections. It changed my object declaration method, some code ordering, unnecessary ';'s standardizing my indents. The Result: The same. The same variables are dropped and the same output is returned.
Here is the full code:
#target photoshop
app.bringToFront();
prefs = new Object();
prefs.db_file = "";
prefs.bk_file = "";
prefs.text = new Object();
prefs.text.top = 0.6;
prefs.text.bottom = 0.9;
prefs.text.padding = 0.05;
prefs.text.size = 12;
prefs.text.shadow = true;
function main() {
Dialogue();
var db_file2 = new File(prefs.db_file);
db_file2.open('r');
var data = Array();
var str = "";
var data_str = "";
while(!db_file2.eof) {
str = db_file2.readln();
data.push(str.split(","));
data_str += str;
};
db_file2.close();
alert(data_str);
};
function Dialogue() {
var dlg = new Window ("dialog","Create New Slide Set");
dlg.orientation = "row";
dlg.alignChildren = "fill";
dlg.pref_group = dlg.add("group");
dlg.pref_group.orientation = "column";
dlg.pref_group.alignChildren = "fill";
dlg.pref_group.db_val = dlg.pref_group.add("edittext",undefined,prefs.db_file);
dlg.pref_group.db_find = dlg.pref_group.add("button",undefined,"select data file");
dlg.pref_group.db_find.onClick = function() {
selectedFile = File.openDialog("Please select CSV file.","CSV File:*.csv");
if(selectedFile != null) {
dlg.pref_group.db_val.text = decodeURI(selectedFile.fsName);
prefs.db_file = dlg.pref_group.db_val.text;
};
};
dlg.pref_group.db_val.onChange = function() {
prefs.db_file = dlg.pref_group.db_val.value;
alert("db_file has been changed!");
};
dlg.pref_group.bk_val = dlg.pref_group.add("edittext",undefined,prefs.bk_file);
dlg.pref_group.bk_find = dlg.pref_group.add("button",undefined,"select background image");
dlg.pref_group.bk_find.onClick = function() {
selectedFile = File.openDialog("Please select PNG file.","Image File:*.png");
if(selectedFile != null) {
dlg.pref_group.bk_val.text = decodeURI(selectedFile.fsName);
prefs.bk_file = dlg.pref_group.bk_val.text;
};
};
dlg.pref_group.bk_val.onChange = function() {
prefs.bk_file = dlg.pref_group.bk_val.value;
};
dlg.pref_group.tt_grp = dlg.pref_group.add("group");
dlg.pref_group.tt_grp.orientation = "row";
dlg.pref_group.tt_grp.alignChildren = "fill";
dlg.pref_group.tt_grp.tt = dlg.pref_group.tt_grp.add("statictext",undefined,"Text Top");
dlg.pref_group.tt_grp.tt_dsp = dlg.pref_group.tt_grp.add("edittext",undefined,prefs.text.top);
dlg.pref_group.tt_grp.tt_dsp.preferredsize = [100,200];
dlg.pref_group.tt_grp.tt_dsp.onChange = function() {
prefs.text.top = dlg.pref_group.tt_grp.tt_dsp.value;
};
dlg.pref_group.bt_grp = dlg.pref_group.add("group");
dlg.pref_group.bt_grp.orientation = "row";
dlg.pref_group.bt_grp.alignChildren = "fill";
dlg.pref_group.bt_grp.bt = dlg.pref_group.bt_grp.add("statictext",undefined,"Text bottom");
dlg.pref_group.bt_grp.bt_dsp = dlg.pref_group.bt_grp.add("edittext",undefined,prefs.text.bottom);
dlg.pref_group.bt_grp.bt_dsp.preferredsize = [100,200];
dlg.pref_group.bt_grp.bt_dsp.onChange = function() {
prefs.text.bottom = dlg.pref_group.bt_grp.bt_dsp.value;
};
dlg.pref_group.pd_grp = dlg.pref_group.add("group");
dlg.pref_group.pd_grp.orientation = "row";
dlg.pref_group.pd_grp.alignChildren = "fill";
dlg.pref_group.pd_grp.pd = dlg.pref_group.pd_grp.add("statictext",undefined,"Padding");
dlg.pref_group.pd_grp.pd_dsp = dlg.pref_group.pd_grp.add("edittext",undefined,prefs.text.padding);
dlg.pref_group.pd_grp.pd_dsp.preferredsize = [100,200];
dlg.pref_group.pd_grp.pd_dsp.onChange = function() {
prefs.text.padding = dlg.pref_group.pd_grp.pd_dsp.value;
};
dlg.pref_group.sd_grp = dlg.pref_group.add("group");
dlg.pref_group.sd_grp.orientation = "row";
dlg.pref_group.sd_grp.alignChildren = "fill";
dlg.pref_group.sd_grp.sd = dlg.pref_group.sd_grp.add("statictext",undefined,"Shadow");
dlg.pref_group.sd_grp.sd_dsp = dlg.pref_group.sd_grp.add("checkbox",undefined,"");
dlg.pref_group.sd_grp.sd_dsp.value = prefs.text.shadow;
dlg.pref_group.sd_grp.sd_dsp.onChange = function() {
prefs.text.shadow = dlg.pref_group.sd_grp.sd_dsp.value;
};
dlg.ok_group = dlg.add('group');
dlg.ok_group.orientation = "column";
dlg.ok_group.ok_btn = dlg.ok_group.add("button",undefined,"ok");
dlg.ok_group.ok_btn.onClick = function() {
prefs.text.shadow = dlg.pref_group.sd_grp.sd_dsp.value;
prefs.text.padding = dlg.pref_group.pd_grp.pd_dsp.value;
prefs.text.bottom = dlg.pref_group.bt_grp.bt_dsp.value;
prefs.text.top = dlg.pref_group.tt_grp.tt_dsp.value;
prefs.bk_file = dlg.pref_group.bk_val.value;
prefs.db_file = dlg.pref_group.db_val.value;
dlg.close(0);
};
dlg.center();
dlg.show();
};
main();
it was so simple...
'edittext' boxes don't have .value properties they have .text properties, trying to access .value returned a null and destroyed the variable.
my research took me into a lot of areas, syntax conventions, JSlint, object definitions, ironically looking into a different problem (onChange functions aren't being called) made me realize that the only variables that weren't being disregarded were the shadow checkbox, and the font size parameter, but the font size parameter wasn't being edited at all at this point, and the shadow was the only thing being defined by a checkbox. Lesson learned: when something is partially working compare the similarities of the working part

Categories

Resources