I'm trying to create a Google sheets script which I hear is complete Javascript so I'm told. I'm just trying to create a list of quests relevant to an item in an online game by parsing the HTML in the spreadsheet.
Example: http://everquest.allakhazam.com/db/item.html?item=14295
Ideally in this case it should bring across the 4 quest names, their location and the quest ID (which can be found within the URL in the source code). But I'm just trying to pull the quest ID at the moment as can be found below.
function myFunction(itemid) {
var regexp = /quest.html\?quest\=(.*)"/;
var page = UrlFetchApp.fetch('http://everquest.allakhazam.com/db/item.html?item=' + itemid).getContentText();
var matches = [];
var number = page.match(/<li><a href="\/db\/quest.html\?quest\=(.*)"/);
for (var i in number) {
matches.push(number[i]);
}
return matches;
}
But the script just seems to hang on 'Loading..' and doesn't do anything. If I add 'return number just after the page.match it returns the first quest ID fine.. so it seems it may be related with pushing to the array which is causing the issues.
It is better not to parse HTML as text. You can use a formula with importxml function to get your data using XPath:
=importxml("http://everquest.allakhazam.com/db/item.html?item=14295";"//div[#id='quest']//b|//div[#id='quest']/ul/li/a|//div[#id='quest']/ul/li/a/#href")
Related
I'm kinda new to coding and I'm trying to learn javascript by using it with google apps. I've figured out a few things trying to do my current project, but I seem to have gotten stuck.
I am attempting to create a program through google sheets that works sort of like a budgeting app, where I import data from my bank, run the program and it searches the data, changes the descriptions based on the content and adds a categorization.
I have figured out a good method for find and replace, but the problem I'm running into is that it only replaces part of the string instead of the whole thing. what i would like for it to do is search the data, if it finds a word that matches one of the cases i have entered, it will delete the entire string and replace it with a new description that I designate.
Here's what i have so far
function replaceStrings(){
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("D1:D" + sheet.getLastRow());
var data = range.getValues();
for (var i = 0; i<data.length; i++) {
if (data[i][1] != "") {
switch (data[i][1]) {
case data.indexOf('MCDONALD\'S') >-1 :
data[i][1].replace(data[i][1],'McDonalds');
break;
}
}
}
range.setValues(data)
}
this is based off of a find and replace function that i had worked out, not sure if I can include the "data[i][0]" in a replace function like that but I have also tried deleting the string and appending the new text but that didn't work either.
When I run this I don't get any error messages, but nothing happens.
I don't know what your data looks so I used some of my own but this technique seems to work fine for me. I used getDataRange and my own indexes but you can modify whatever you need. Or if you wish you can share your spreadsheet and I can customize to your exact requirements.
function replaceStrings()
{
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getDataRange()
var data = range.getValues();
for (var i = 0; i<data.length; i++)
{
if(data[i][1].match(/firstMatch/))
{
data[i][1]='replacement1';
}
if(data[i][1].match(/secondMatch/))
{
data[i][1]='replacement2';
}
}
range.setValues(data);
}
Your can use anything you want for the match strings. I happen to use regular expressions and if you find a match you can replace the entire data element with anything you wish.
The context: I need to process/correct many text documents containing multiple particular textual errors, highlight keywords in 'bold' and then output the result. I have a Google spreadsheet with two worksheets: one with two columns of 'wrong wordforms' and 'replacement wordforms' (2d array) that I intend to add to over time and use it as a datastore to 'call from;' the other, a single-column collection of words (1d array) I designate "keywords" to check for and then highlight in the target documents.
Things I've tried that worked: I used a basic array iteration loop from a beginner video (I can't add more links yet, I apologize) and swapped in body.replaceText() for the sendEmail(), successfully, to process the corrections from my "datastore" into my target document, which works nearly perfectly. It ignores text values without the exact same case...but that's a problem for another day.
function fixWords() {
// Document to edit
var td = DocumentApp.openById('docId1');
// Document holding comparison datastore
var ss = SpreadsheetApp.openById('docId2');
// Create data objects
var body = td.getBody();
var sheet = ss.getSheetByName("Word Replacements");
var range = sheet.getDataRange();
var values = range.getValues();
// Create a loop (iterate through the cell data)
for (i=1;i<values.length;i++) {
fault = values[i][0];
solution = values[i][2];
body.replaceText(fault, solution);
}
}
Things I've tried that fail: I then tried just swapping out values for setBold() with the replaceText() code, but the closest I got was the first instance of a keyword from the array would be styled correctly, but no further instances of it...unlike ALL of the instances of an incorrectly spelled word being corrected from the Word Replacements array using the fixWords function.
I found the 'highlightTextTwo' example here at stackoverflow which works very well, but I couldn't figure out how to swap in an external data source or force the included different iteration loop to work in my favor.
I've scanned the GAS reference, watched Google developer videos for snippets that might apply...but clearly I'm missing something that's probably basic to programming. But I honestly don't know why this isn't as easy as the body.replaceText() functionality.
function boldKeywords() { // https://stackoverflow.com/questions/12064972
// Document to edit
var doc = DocumentApp.openById('docId1');
// Access the keyword worksheet, create objects
var ss = SpreadsheetApp.openById('docId2');
var sheet = ss.getSheetByName("Keywords");
var range = sheet.getDataRange();
var values = range.getValues();
var highlightStyle = {};
highlightStyle[DocumentApp.Attribute.BOLD] = 'true';
for (i=1; i<values.length; ++i) {
textLocation = values[i];
if (textLocation != null && textLocation.getStartOffset() != -1) {
textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
}
}
}
This throws out 'TypeError: Cannot find function getStartOffset in object DIV. (line 15, file "boldIt").' I guess this means that by just blindly swapping in this code, it's looking in the wrong object...but I cannot figure out why it works for x.replaceText() and not for x.setAttributes() or x.setBold or .getElement().getText().editAsText()...there just doesn't seem to be a "Learn Google Apps Script example" that deals with something this low on a scale of mundane, uninteresting use cases...enough for me to figure out how to direct it to the right object, and then manipulate the "if statement" parameters to get the behavior I need.
My current brick wall: I spotted this example, again, Text formatting for strings in Google Documents from Google Apps Script, and it seemed promising, even though the DocsList syntax has been deprecated (I'm fairly sure). But now I get "bold is not defined" thrown at me. Bold...is not defined. :: mouth agape ::
function boldKeywords() {
// Access the keyword worksheet, create objects
var ss = SpreadsheetApp.openById('docId1');
var sheet = ss.getSheetByName("Keyterms");
var range = sheet.getDataRange();
var values = range.getValues();
// Open target document for editing
var doc = DocumentApp.openById('docId2');
var body = doc.getBody();
// Loop function: find given keyword value from spreadsheet in target document
// and then bold it (highlight with style 'bold')
for (i=1; i<values.length; ++i) {
keyword = values[i];
target = body.findText(keyword);
body.replaceText(target,keyword);
text = body.editAsText();
text.setBold(text.startOffset, text.endOffsetInclusive, bold);
}
}
I will happily sacrifice my firstborn so that your crops may flourish for the coming year in exchange for some insight.
I use this for my scripts, the setStyleAttribute method.
Documentation : https://developers.google.com/apps-script/ui_supportedStyles
Example :
TexBox.setStyleAttribute("fontWeight", "bold");
The bold parameter is a Boolean data type. You need to use the word true or false.
Replace "bold" with "true".
text.setBold(text.startOffset, text.endOffsetInclusive, true);
Check out the "Type" column in the documentation:
Google Documentation - setBold
A javascript issue again, I can't understand the problem. I use Appinventor to transfer a message to an html file using webviewstring. the message sent is here, starting with 1%mc:
As you can see, it jumps to the next line because everyline has an \n at the end.
In javascript, I try to create an array of arrays using this code:
var wvdata = window.AppInventor.getWebViewString().split('\n');
var urlArray = [];
for (var i in wvdata){
urlArray.push(wvdata[i].split('%'));
}
I don't know what's wrong with it, since it was running fine when I splitted it with a ,. Just because I need to use comma in some places, I changed my splitters to % but this doesn't work. I use script blocks like this one to assign data inside the array to items, but now it just shows the default data, as if there were nothing inside urlArray.
document.getElementById("testname0").innerHTML = urlArray[0][2];
I have a page that has an unordered list on it. I am populating the list via javascript like this:
var vidList = document.getElementById("vidList");
var li = document.createElement("li");
li.id = "videoPlayer" + count;
var runat = document.createAttribute("runat");
runat.value = "server";
li.setAttributeNode(runat);
// Here I insert a flash video stream into li
vidlist.appendChild(li);
This works as far as creating the elements and rendering them to the page. The issue is accessing them later. Since they are video streams I want to remove them when they are no longer valid streams. In my Visual Basic code behind I have the following code:
For videoNumber As Integer = 1 to numVideos
Dim li = vidList.FindControl("videoPlayer" & videoNumber.toString())
// Check if the stream is valid and delete it if it isn't
Next
When I debug the call to FindControl returns Nothing. So I looked through the local variables and found that my list had 5 elements all of which are Nothing. I looked at both this question and this one, but neither quite worked for my needs. Is there a reason that the list items are coming into the code behind as null values?
Request.Form['videoPlayer' + count]
More generally you can use Request.Form['clientID'] for dynamically created controls.
new here and hit a roadblock, been searching but can't find the answer with my skill set. Task is pretty simple, I want to parse this http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json which is from a weather station. I have used the W3C tutorial but just can't seem to parse this file, but http://json.parser.online.fr has no problem. All the looping parse examples just give me alert after alert.
All I want is the ability to select temp[0] (out of god knows how many) for example via javascript and have it display on a website. I'm really lost, tried searching and if I've missed the goldmine then my bad. Thanks!
Example code
var text = '[{"humidity":"42.8000","stationtime":"2014-07-06 19:43:52","temp":"23.3000","timestamp":"2014-07-06T09:44:07.918Z"},{"humidity":"43.0000","stationtime":"2014-07-06 19:42:57","temp":"23.2000","timestamp":"2014-07-06T09:42:22.003Z"},{"humidity":"43.2000","stationtime":"2014-07-06 19:42:36","temp":"23.3000","timestamp":"2014-07-06T09:42:51.737Z"}]';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.temp[0];
First, you need to parse the incoming string as below:
temp_arr = JSON.parse(json_string);
Just loop over the temp_arr array, and in each iteration of loop you'll have one object (tobj). For example, like this:
{"humidity":"40.9000","stationtime":"2014-07-06 21:21:03","temp":"22.6000","timestamp":"2014-07-06T11:20:27.231Z"}
All you have to do is, access it like tobj.temp and use it to display on page.
I have written a jquery implementation at: http://jsfiddle.net/DNH5n/2/
Jquery makes working with JSONP much easier heres an example (http://jsfiddle.net/icodeforlove/9mBsr/)
$.getJSON('http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json?callback=?', function (data) {
data.forEach(function (item) {
$('body').append(JSON.stringify(item));
});
})
update again
heres another example using your code (http://jsfiddle.net/icodeforlove/9mBsr/2/)
var text = '[{"humidity":"42.8000","stationtime":"2014-07-06 19:43:52","temp":"23.3000","timestamp":"2014-07-06T09:44:07.918Z"},{"humidity":"43.0000","stationtime":"2014-07-06 19:42:57","temp":"23.2000","timestamp":"2014-07-06T09:42:22.003Z"},{"humidity":"43.2000","stationtime":"2014-07-06 19:42:36","temp":"23.3000","timestamp":"2014-07-06T09:42:51.737Z"}]';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj[0].temp;