Javascript generating anchors quote issue - quote

I'm new to this site and new to Javascript, however I'm been coding in C for some years, and I ran into a problem that totally blows my mind.
I want to make a tool for myself (a very simple code generating tool). I want to generate html code and in a displayable manner, because the final product would be a static page (no javascript). So I tried to solve it with basic string manipulation.
The task and the code is so simple I'll just post it here.
Javascript with it's corresponding tags:
<script>
function ConvertListToGallery()
{
var cont = document.getElementById("gallery_generator_input");
var eof_link;
var eof_title;
var eof_descr;
var lines = [];
var tokens = [];
var i, k;
var result = document.getElementById("gallery_generator_output");
var link;
var lofasz = [];
if(cont)
{
lines = cont.value.split('\n');
lofasz = cont.value.split('"');
console.log(lofasz[0]);
result.innerHTML = "";
for( i = 0; i < lines.length; i++ )
{
tokens = lines[i].split(" + ");
for( k = 0; k < tokens.length; k++ )
{ console.log(tokens[k]); }
link = tokens[0];
result.innerHTML += '<img src=' + link + '/>';
}
document.getElementById("gallery_generator_result").value=result.innerHTML;
document.getElementById("gallery_convert").innerHTML = "Done!";
document.getElementById("gallery_convert").onclick = "";
}
}
</script>
The input:
https://drive.google.com/uc?id=0B3ju3vX1o4OuY0RaaDJKWnlRN1U + title +
desc https://drive.google.com/uc?id=0B3ju3vX1o4OuSC1hNFQwUV9IWlE +
title2 + desc2
And the output after running the script:
<img src="https://drive.google.com/uc?id=0B3ju3vX1o4OuY0RaaDJKWnlRN1U/"><img src="https://drive.google.com/uc?id=0B3ju3vX1o4OuSC1hNFQwUV9IWlE/">
It's like something automatically put quotes around the links. Sorry, I have tried so many things I can't remember now, but as I remember this "auto-quoting" thing only happens with links and it causes all sorts of problem in the resulting code (for example the '/' slips inside the quotes). And all other problems were caused by this behavior (I can't assign title and other attributes inside the img tag).
Additional html:
<form>
<textarea id="gallery_generator_input" style = "width:800px;"></textarea></form>
<div id="gallery_generator_output" style="border:solid; max-height:500px; overflow:auto;">
</div>
<textarea id="gallery_generator_result" style = "width:800px;"></textarea>
<div onclick = "ConvertListToGallery();" id="gallery_convert">Convert!</div>
Thank you for any hints in advance!
EDIT: removed the misleading WOW thing.
The desired result is simply a valid html image code.

Change this line
result.innerHTML += '<img src=' + link + '!!WOW>';
to this
result.innerHTML += '<img src="' + link + '!!WOW"/>';
also you can urlencode the exclamation marks if they are a problem:
result.innerHTML += '<img src="' + link + '%21%21WOW"/>';

Sorry for the late follow-up, but it turned out that writing to the innerHMTL caused the issue (I'm still not sure if writing to innerHTML has some kind of obscure code fixing/completion feature). If I accumulate the HTML in a separate variable THEN assign it to the innerHTML has no issues.
I know that it's not the best practice to make dynamic code like that (the elements don't get added to the DOM tree), but for my use it's simpler to make the code this way, since it's only a tool for me to generate static pages.

Related

Looping over a dynamic range in Google apps script to replace certain values

I've been getting problems trying to reference a dynamic range in google sheets to apply my function to: essentially replacing special characters and empty cells within a given data range with 0s, works perfectly if I gave it a static range but cant seem to do a dynamic one. Thanks alot for any help offered
Code thus far:
function replaceValues() {
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var lastRow = sheet1.getDataRange().getLastRow()
var firstRow = sheet1.getDataRange().getRow("B2")
var targetValue1 = '-'
var targetValue2 = ''
var targetValue3 = '$'
var subValue = 0
for(var i =0; i=targetValue1; i++); {
var valueRng = sheet1.getRange(firstRow,lastRow);
var newValues = valueRng.getValues()[i].setValues(subValue);
}
}
Select the range before going the the menu and executing the function or build a modeless dialog and you can make the selection and capture on the custom dialog with a button click.
Demo:
If you have a range, you can do search and replace inside it this way:
range.createTextFinder('aaa').replaceAllWith('b');
Or with RegExp:
range.createTextFinder('a+').useRegularExpression(true).replaceAllWith('b');
I still don't understand what exactly you're trying to gain. So here is a guess how your script might look like:
function replaceValues() {
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var range = sheet1.getDataRange(); // is the range dynamic enough?
// replace '$' and '-' with '0'
range.createTextFinder("[\$-]").useRegularExpression(true).replaceAllWith('0');
// replace '' with '0'
var data = range.getValues();
data.forEach((row,r) => row.forEach((cell,c) =>
data[r][c] = data[r][c].toString().replace(/^$/,'0')));
range.setValues(data);
}

InDesign Endnote Automation

I'm using this simple script to grab text wrapped in [ENDNOTE][/ENDNOTE] tags and make them into actual InDesign endnotes. The problem I'm having is that only the first 4 characters are being placed between the endnote markers (see screenshot below), any idea why this is happening, or how to make it work right?
var doc = app.activeDocument;
function footnoteToEndnotes () {
app.findGrepPreferences = null;
app.findGrepPreferences.findWhat = '\\[ENDNOTE\\](.+?)\\[\\/ENDNOTE\\]';
var endnote,
fnotes = doc.findGrep();
for (var i = fnotes.length-1; i >= 0; i--) {
var taggedText = fnotes[i].contents.replace('[ENDNOTE]', '').replace('[/ENDNOTE]', '');
endnote = fnotes[i].insertionPoints[0].createEndnote();
endnote.texts[0].contents = taggedText;
fnotes[i].remove();
}
}
if (parseInt (app.version) < 13) {
alert ('This script requires InDesign CC2018 or later');
exit();
}
doc.endnoteOptions.frameCreateOption = EndnoteFrameCreate.NEW_PAGE;
footnoteToEndnotes();
So, when I set the content of insertionPoints[0], the full endnote ended up inside the endnote markers. But, there was an extraneous tab character at the end of the string... I stripped it out and it's working like I want!
I replaced this line:
endnote.texts[0].contents = taggedText;
With these:
endnote.texts[0].insertionPoints[0].contents = taggedText;
endnote.texts[0].contents = endnote.texts[0].contents.replace('\t', '');

Google Places Photos .GetUrl is adding width and height to url

I'm trying to get images from google places. All is working for details: reviews, address... but when I try to get photos, I get a 404.
if(place.photos != null){
for(var i = 0; i < place.photos.length; i++){
var str = place.photos[i].getUrl({"maxWidth": 100, "maxHeight": 100});
var res = str.replace("w100-h100-p", "p");
self.pacPhotos.push({
id : res
});
}
}else {
console.log("no photo");
}
}
This will return the list ok but the URL is formatted wrong. it comes out like this.
" https://lh3.googleusercontent.com/w100-h100-p/AF1QipN3xzffYDPCyEIWnvAQGd3RwNs2C14sVlSqrrAh=k "
What I gather it wants is this.
" https://lh3.googleusercontent.com/p/AF1QipN3xzffYDPCyEIWnvAQGd3RwNs2C14sVlSqrrAh=k "
The only difference is the "w100-h100-"
*** There is a great work-around here from "Sulyman". I know it's not a long term solution as I'm sure google will fix their results (as discussed here Place API - getting place photo as marker icon )
For now I've adjusted the code above to reflect Sulymans suggestion. ***
it seems like every API Key generates different path
for example you got w100-h100-p and i got w200-p
and the good news that this section whatever it is...is fixed so you can replace it with another string which is p
var str = place.photos[0].getUrl();
var res = str.replace(""w100-h100-p", "p");
or you can delete the w100-h100-

Break line in long label text

Is there any trick to break a label text? Because '\n' '\r' '\n\r' don't work.
Many Thanks
if you use those 2 parameters you do what you want don't you ?
app.createLabel(text).setWidth(width).setWordWrap(true)
here is an example (among other widgets ;-):
function showurl() {
var app = UiApp.createApplication();
app.setTitle("Anchor in a popup ;-)");
var panel = app.createFlowPanel()
var image = app.createImage('https://sites.google.com/site/appsscriptexperiments/home/photo.jpg').setPixelSize(50, 50)
var link = app.createAnchor('This is your link', 'https://sites.google.com/site/appsscriptexperiments/home');
var lab = app.createLabel("wrap it because it's too narrow").setWidth(90).setWordWrap(true);
var quit = app.createButton('quit');
panel.add(image).add(link).add(lab).add(quit);
app.add(panel);
var doc = SpreadsheetApp.getActive();
doc.show(app);
}
EDIT : I found an old post(on the Google group forum, thanks again Henrique ;-) about breaking lines in toast messages and here is the code I used for that case... the principle should work for Labels too but I didn't try.
To use it, just use \n (where you want to break the line) in a variable containing your text and pass it through this function. (there are some comment in the script to explain)
function break_(msg){
var temp = escape(msg);// shows codes of all chars
msg = unescape(temp.replace(/%20/g,"%A0")); // replace spaces by non break spaces
temp = msg.replace("\n"," "); // and replace the 'newline' by a normal space
return temp; // send back the result
}
Would something like this work?
//takes a line of text and returns a flex table broken by \n
function breakLabel(text) {
var app = UiApp.getActiveApplication();
var flexTable = app.createFlexTable();
text = text.split('\n'); // split into an array
for (var i=0; i<text.length; i++){
flexTable.setWidget(i, 0, app.createLabel(text[i].toString()));
}
return flexTable;
}
Adding them to a vertical panel helps as well (not the way you want, but still..):
var vPanel = app.createVerticalPanel().setSize(100,100);
var label = app.createLabel('predominantly blabla blala blabla');
app.add(vPanel.add(label));
See reference
For anyone just now stumbling upon this, the best solution seems to be creating an HTML output for anything that needs line breaks.
Documentation
var htmlApp = HtmlService
.createHtmlOutput('<p>A change of speed, a change of style...</p>')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('My HtmlService Application')
.setWidth(250)
.setHeight(300);
SpreadsheetApp.getActiveSpreadsheet().show(htmlApp);
// The script resumes execution immediately after showing the dialog.

Reading text using selenium webdriver(xpath)

I'm using selenium to get some text on my webpage using xpath.
The page tag structure is as follows -
<span id="data" class="firefinder-match">
Seat Height, Laden
<sup>
<a class="speckeyfootnote" rel="p7" href="#">7</a>
</sup>
</span>
If I use the following code -
driver.findElement(By.xpath("//span[#id='data']")).getText();
I get the result = Seat Height, Laden 7
But I want to avoid reading the text within the <sup> tags and get the
result Seat Height, Laden
Please let me know which xpath expression I can use to get my desired result.
I don't know about any way to do this in Selenium, so there's my JS solution. The idea is to get all children of the element (including the text nodes) and then select only the text nodes. You might need to add some .trim() (or JS equivalent) calls to get rid of unneeded spaces.
The whole code:
WebElement elem = driver.findElement(By.id("data"));
String text;
if (driver instanceof JavascriptExecutor) {
text = ((JavascriptExecutor)driver).executeScript(
"var nodes = arguments[0].childNodes;" +
"var text = '';" +
"for (var i = 0; i < nodes.length; i++) {" +
" if (nodes[i].nodeType == Node.TEXT_NODE) {" +
" text += nodes[i].textContent;" +
" }" +
"}" +
"return text;"
, elem);
}
And just the JS for better readability.
var nodes = arguments[0].childNodes;
var text = '';
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].nodeType == Node.TEXT_NODE) {
text += nodes[i].textContent;
}
}
return text;

Resources