I have a text file containing 100 words. I would like my programme to select a random number of words between 1 - 7 from the 100 words in the text file to print.
I know how to get a random number
var ranNum = Math.floor(Math.random() * 7) +1 ;
but not sure how to get my programme to select a random amount of words as determined by ranNum
function randomWord(){
var fs = require('fs');
var readME = fs.readFileSync('text.txt', 'utf8', function(err,data) {
//reads text file
console.log(data);
});
console.log(readME);
//returns a random num between 1-9
var ranNum = Math.floor(Math.random() * 7) + 1;
console.log(ranNum); //prints out that number
}
randomWord();
I want my programme to select a random amout of words from the text file each time it is run
If you want to get n random words from a text file and the text file consists of a string like this:
apple, orange, banana, pear, elephant, horse, dog, cow, brazil, england, france
You can use the following code:
// declare 'require()' imports at the top of your script
var fs = require('fs');
function randomWords(words){
// Since you use 'readFileSync', there is no callback function
var readME = fs.readFileSync('text.txt', 'utf8');
// Split the string into an array
var wordArr = readME.split(', ');
// Check if the specified amount of words is bigger than
// the actual array length (word count) so we don't end
// up in an infinite loop
words = words > wordArr.length ? wordArr.length : words;
// Create empty array
var randWords = [];
// push a random word to the new array n times
for (let i = 0; i < words; i++){
// new random number
let newRandom;
do {
// New random index based on the length of the array (word count)
let rand = Math.floor(Math.random() * wordArr.length);
newRandom = wordArr[rand];
}
// Make sure we don't have duplicates
while (randWords.includes(newRandom));
// Add the new word to the array
randWords.push(newRandom);
}
// Join the array to a string and return it
return randWords.join(', ');
}
// You can pass the amount of words you want to the function
console.log(randomWords(5));
I commented the code for clarification.
Working Repl.it Demo: Demo
I am looking for a solution to search for certain strings in a Google Sheet and, when found, replace them with another string from a list in another sheet.
For better understanding, I prepared a Sheet for you:
https://docs.google.com/a/vicampo.de/spreadsheets/d/1mETtAY72K6ST-hg1qOU9651265nGq0qvcgvzMRqHDO8/edit?usp=sharing
So here's the exact task I want to achieve:
In every single cell in column A of sheet "Text", look for the strings given in column A in sheet "List" and, when found, replace it with the corresponding string in column B of the sheet "List".
See my Example: Look in cell A1 for the string "Lorem" and replace it with "Xlorem", then look for the string "Ipsum" and replace it with "Xipsum", then look for the string "amet" and replace it with "Xamet" then move on to cell B1 and start again looking for the strings...
I have tried different functions and managed to do this with a function for one cell. But how to do it in a loop?
Thanks everyone who is interested in helping out with this problem!
Although there must be 'nicer' solutions, a quick solution (as long is the number of cells with the words you want replaced is not too long), would be:
=ArrayFormula(regexreplace(regexreplace(regexreplace(A1:A; List!A1; List!B1); List!A2; List!B2); List!A3; List!B3))
Probably the best for you, in this case, should be creating a new function to your Google Spreadsheet. It tends to be, in the general case, more simple, clear and powerfull than that kind of complex formulas that should do the same.
In this particular case, I have the same problem, so you can use the same function:
Click on "Tools" menu, then click on the "Script Editor" option. Into the script editor, erase the draft and paste this function:
function preg_quote( str ) {
// http://kevin.vanzonneveld.net
// + original by: booeyOH
// + improved by: Ates Goral (http://magnetiq.com)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// * example 1: preg_quote("$40");
// * returns 1: '\$40'
// * example 2: preg_quote("*RRRING* Hello?");
// * returns 2: '\*RRRING\* Hello\?'
// * example 3: preg_quote("\\.+*?[^]$(){}=!<>|:");
// * returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:'
return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}
function ARRAYREPLACE(input,fromList,toList,caseSensitive){
/* default behavior it is not case sensitive */
if( caseSensitive === undefined ){
caseSensitive = false;
}
/* if the from list it is not a list, become a list */
if( typeof fromList != "object" ) {
fromList = [ fromList ];
}
/* if the to list it is not a list, become a list */
if( typeof toList != "object" ) {
toList = [ toList ];
}
/* force the input be a string */
var result = input.toString();
/* iterates using the max size */
var bigger = Math.max( fromList.length, toList.length) ;
/* defines the words separators */
var arrWordSeparator = [ ".", ",", ";", " " ];
/* interate into the lists */
for(var i = 0; i < bigger; i++ ) {
/* get the word that should be replaced */
var fromValue = fromList[ ( i % ( fromList.length ) ) ]
/* get the new word that should replace */
var toValue = toList[ ( i % ( toList.length ) ) ]
/* do not replace undefined */
if ( fromValue === undefined ) {
continue;
}
if ( toValue == undefined ) {
toValue = "";
}
/* apply case sensitive rule */
var caseRule = "g";
if( !caseSensitive ) {
/* make the regex case insensitive */
caseRule = "gi";
}
/* for each end word char, make the replacement and update the result */
for ( var j = 0; j < arrWordSeparator.length; j++ ) {
/* from value being the first word of the string */
result = result.replace( new RegExp( "^(" + preg_quote( fromValue + arrWordSeparator[ j ] ) + ")" , caseRule ), toValue + arrWordSeparator[ j ] );
/* from value being the last word of the string */
result = result.replace( new RegExp( "(" + preg_quote( arrWordSeparator[ j ] + fromValue ) + ")$" , caseRule ), arrWordSeparator[ j ] + toValue );
/* from value in the middle of the string between two word separators */
for ( var k = 0; k < arrWordSeparator.length; k++ ) {
result = result.replace(
new RegExp(
"(" + preg_quote( arrWordSeparator[ j ] + fromValue + arrWordSeparator[ k ] ) + ")" ,
caseRule
),
/* need to keep the same word separators */
arrWordSeparator[ j ] + toValue + arrWordSeparator[ k ]
);
}
}
/* from value it is the only thing in the string */
result = result.replace( new RegExp( "^(" + preg_quote( fromValue ) + ")$" , caseRule ), toValue );
}
/* return the new result */
return result;
}
Just save your script and the new function it will be available to you. Now, you have the function that replaces all the first values list by the second value list.
=ARRAYREPLACE(C2;A1:A4;B1:B4)
for example, takes the C2 text and replaces all the elements found in the A1:A4 list by the equivalent into the B1:B4 list.
Copy Sample File With Explanation
Problem
The challenge is:
Find & Replace multiple values in the input of multiple cells.
ArrayFormula's
Solutions which I account as Array-Solution must be:
based on open ranges
no need to drag the formula down
no need to modify the formula when new items in lists appear
These tests must be passed:
Is ArrayFormula
User can set Case Sensitivity
Replaces Emojis
Replaces Special Chars $\[]. etc.
CrashTest. Works for 10K rows of data
CrashTest. Works for 2K replacements
Script
I recommend using the not-regex-based script in this case. This algorithm finds and replaces text by chars:
Usage
Use as a regular formula from sheet:
=substitutes(A12:A;List!A1:B)
Code
Save this code to use the formula above:
/**
* Substitutes in every entry in array
* Text from prefilled array
*
* #param {array} input The array of strings.
* #param {array} subTable The array of string pairs: search texts / replace texts.
* #param {boolean} caseSensitive [optional=false]
* TRUE to match Apple and apple as different words
* #return The input with all replacement made
* #customfunction
*/
function substitutes(input, subTable,caseSensitive) {
// default behavior it is not case sensitive
caseSensitive = caseSensitive || false;
// if the input is not a list, become a list */
if( typeof input != "object" ) {
input = [ input ];
}
var res = [], text;
for (var i = 0; i < input.length; i++) {
// force each array element in the input be a string
text = input[i].toString();
for (var ii = 0; ii < subTable.length; ii++) {
text = replaceAll_(
text,
subTable[ii][0],
subTable[ii][1],
caseSensitive);
}
res.push(text);
}
return res;
}
/***
* JavaScript Non-regex Replace
*
* Original code sourse:
* https://stackoverflow.com/a/56989647/5372400
*/
function replaceAll_(str, find, newToken, caseSensitive) {
var i = -1;
// sanity check & defaults
if (!str) {
// Instead of throwing, act as
// COALESCE if find == null/empty and str == null
if ((str == null) && (find == null))
return newToken;
return str;
}
if (!find || find === ''){ return str; }
if (find === newToken) { return str; }
caseSensitive = caseSensitive || false;
find = !caseSensitive ? find.toLowerCase() : find;
// search process, search by char
while ((
i = (!caseSensitive ? str.toLowerCase() : str).indexOf(
find, i >= 0 ? i + newToken.length : 0
)) !== -1
) {
str = str.substring(0, i) +
newToken +
str.substring(i + find.length);
}
return str;
}
Monster Formula
I've used the RegEx algorithm to solve it with native functions. This method is not recommended as it slows down your Worksheet.
The formula is:
=INDEX(SUBSTITUTE(REGEXREPLACE(TRANSPOSE(QUERY(TRANSPOSE(IFERROR(SPLIT(SUBSTITUTE(TRANSPOSE(QUERY(TRANSPOSE(IFERROR(VLOOKUP(SPLIT(REGEXREPLACE(A12:A;SUBSTITUTE(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1");"𑇡";"(.*)");INDEX(REGEXREPLACE(TRIM(TRANSPOSE(QUERY(TRANSPOSE(IF(SEQUENCE(COUNTA(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2));MAX(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2)))-(SEQUENCE(COUNTA(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2)))-1)*MAX(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2))<=INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2);"𑇣"&SEQUENCE(COUNTA(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2));MAX(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2)))-(SEQUENCE(COUNTA(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2)))-1)*MAX(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2))&"𑇤";));;2^99)));" ?𑇣";"$")));"𑇤");{List!A1:A\List!B1:B};2;)&"𑇩"));;2^99));"𑇩 ";"𑇩")&"𝅘";"𑇩")&SPLIT(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡")&"𝅘";"𑇡")))&"𝅗";;2^99));"𝅗 *";"");"𝅘";""))
Other Solutions
Nested formulas
Nested SUBSTITUTE or REGEXREPLACE formulas as was noted in other answers.
Formulas you need to drag down for the result
Here's a sample formula. Basic logic - split the text into parts → modify parts individually → to join the new result.
This formula must be copied down:
=JOIN(" ";
ArrayFormula(
IFERROR(VLOOKUP(TRANSPOSE(SPLIT(A1;" "));List!A:B;2;0);TRANSPOSE(SPLIT(A1;" ")))))
An improvement on JPV's answer, which is orders of magnitude faster and works with arbitrary query and replacement strings:
=ArrayFormula(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1:A, List!A1, List!B1), List!A2, List!B2), List!A3, List!B3))
Using this format, a 15,000 cell spreadsheet with an 85-length replacement list will update in just a few seconds. Simply assemble the formula string using your scripting language of choice and you're good to go!
With new Labmda and Friends:
=LAMBDA(data,re,with,BYROW(data,LAMBDA(r,if(r="","",REDUCE(r,SEQUENCE(counta(re)),LAMBDA(ini,v,REGEXREPLACE(ini,INDEX(re,v),INDEX(with,v))))))))(C5:C6,E5:E7,F5:F7)
=> Named function
=SUBSTITUTES_RE(list0,list_re,list_with)
↑ This will substitute using regular expressions
substututes
Definition is the same, but REGEXREPLACE is replaced with SUBSTITUTE
Other examples here:
https://docs.google.com/spreadsheets/d/1IMymPZlibT6DX4yzDX4OXj2XBZ48zEl6vBUzIHJIzVE/edit#gid=0
Here is a bit simpler of a script than Thiago Mata's. I modified the script from https://webapps.stackexchange.com/a/46895 to support either single cell or range input
function MSUBSTITUTE(input, subTable)
{
var searchArray = [], subArray = [], outputArray = [];
for (var i = 0, length = subTable.length; i < length; i++)
{
if (subTable[i][0])
{
searchArray.push(subTable[i][0]);
subArray.push(subTable[i][1]);
}
}
var re = new RegExp(searchArray.join('|'), 'g');
/* Check if we got just a single string */
if (typeof( input ) == "string")
{
outputArray.push(input.replace(re, function (match) {return subArray[searchArray.indexOf(match)];}));
}
else /* we got an array of strings */
{
for (var i = 0; i < input.length; i++)
{
/* force each array element in the input be a string */
var text = input[i].toString();
outputArray.push(text.replace(re, function (match) {return subArray[searchArray.indexOf(match)];}))
}
}
return outputArray;
}
I've found a simple way to do this with "ARRAYFORMULA"
You must have one list with the text to find and in a contiguos column, the list you want to replace de data, for example:
#
D
E
1
ToFind
ToReplace
2
Avoc4do
Avocado
3
Tomat3
Tomate
4
On1on
Onion
5
Sug4r
Sugar
then use this formula
=ARRAYFORMULA(FIND(A1:A1000,D1:D5,E1:E5))
A1:A1000 is the original column where you have multiple rows with the word "Avoc4do, Tomat3, On1on, Sugar", ArrayFormula works with a matrix where others formulas can't (formula FIND can't work finding in a matrix, so we use ArrayFormula)
Then you will have a colum with the 1000 rows but now with the "ToReplace" text in order, so now cut and copy in the column A, that's it.
Got it
Lorem ipsum dolor sit xamet Lorem ipsum
= textjoin("";true;ARRAYFORMULA(ifna(vlookup(REGEXEXTRACT(A1;"("®EXREPLACE(A1;"("&(textJOIN("|";true;lookuprange))&")";")($1)(")&")");lookuprange;2;false);REGEXEXTRACT(A1;"("®EXREPLACE(A1;"("&(textJOIN("|";true;lookuprange))&")";")($1)(")&")"))))
Xlorem ipsum dolor sit Xamet Xlorem ipsum
I have a string with 1000 length. I need to split it and assign it to different controls. I do not have any character separator.
Since each string that I am assigning to controls do not contain same length. As of now I am doing it using substring in which i am specifying the length. But its becoming hectic for me as the length is huge.
Please suggest me is there any way to split and assign in simpler way?
You can use this string constructor:
var input = "Some 1000 character long string ...";
var inputChars = input.ToCharArray();
control1.Value = new string(inputChars, 0, 100); // chars 0-100 of input
control2.Value = new string(inputChars, 100, 20); // chars 100-120 of input
control3.Value = new string(inputChars, 120, 50); // chars 120-170 of input
...
Or using Substring:
var input = "Some 1000 character long string ...";
control1.Value = input.Substring(0, 100); // chars 0-100 of input
control2.Value = input.Substring(100, 20); // chars 100-120 of input
control3.Value = input.Substring(120, 50); // chars 120-170 of input
You could also do this
var parts = new []
{
Tuple.Create(0, 100),
Tuple.Create(100, 20),
Tuple.Create(120, 50),
}
var inputParts = parts.Select(p => input.Substring(p.Item1, p.Item2))
.ToArray();
control1.Value = inputParts[0];
control2.Value = inputParts[1];
control3.Value = inputParts[3];
This makes it much easier to maintain as the number of controls grows larger. You can store this list of 'parts' statically, so it can be reused elsewhere in your application without duplicating the code.
If all the controls the same type, you can do this:
var parts = new []
{
new { control = control1, offset = 0, length = 100 },
new { control = control2, offset = 100, length = 20 },
new { control = control3, offset = 120, length = 50 },
}
foreach(var part in parts)
{
part.control.Value = new string(inputChars, part.offset, offset.length);
// or part.control.Value = input.Substring(part.offset, offset.length);
}
You won't get around specifying the information which control gets which part of the string. Once you have this information (let's say they are stored in a control array controls and int array length), you can just loop over the string and do a piecewise Substring:
var controls = { control1, control2, control3, ... };
var lengths = { 100, 20, 5, ... };
int offset = 0;
for (int i = 0; i < controls.length; i++) {
controls[i].Value = myLongString.Substring(offset, lengths[i]);
offset += lengths[i];
}
Obviously, this will fail horribly if myLongString is shorter than the sum of all lengths or the array length of lengths is shorter than the one of controls, but adding some checks for that and throwing a suitable error is left as an exercise to the reader. In addition, the controls must be compatible in the sense that they all derive from the same base class with a common Value property. If that is not the case, you might have to do a few type checks and casts inside the loop.
On the webpage
http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463
It lists prices for a particular item in a game, I wanted to grab the "Current guide price:" of said item, and store it as a variable so I could output it in a google spreadsheet. I only want the number, currently it is "643.8k", but I am not sure how to grab specific text like that.
Since the number is in "k" form, that means I can't graph it, It would have to be something like 643,800 to make it graphable. I have a formula for it, and my second question would be to know if it's possible to use a formula on the number pulled, then store that as the final output?
-EDIT-
This is what I have so far and it's not working not sure why.
function pullRuneScape() {
var page = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var number = page.match(/Current guide price:<\/th>\n(\d*)/)[1];
SpreadsheetApp.getActive().getSheetByName('RuneScape').appendRow([new Date(), number]);
}
Your regex is wrong. I tested this one successfully:
var number = page.match(/Current guide price:<\/th>\s*<td>([^<]*)<\/td>/m)[1];
What it does:
Current guide price:<\/th> find Current guide price: and closing td tag
\s*<td> allow whitespace between tags, find opening td tag
([^<]*) build a group and match everything except this char <
<\/td> match the closing td tag
/m match multiline
Use UrlFetch to get the page [1]. That'll return an HTTPResponse that you can read with GetBlob [2]. Once you have the text you can use regular expressions. In this case just search for 'Current guide price:' and then read the next row. As to remove the 'k' you can just replace with reg ex like this:
'123k'.replace(/k/g,'')
Will return just '123'.
https://developers.google.com/apps-script/reference/url-fetch/
https://developers.google.com/apps-script/reference/url-fetch/http-response
Obviously, you are not getting anything because the regexp is wrong. I'm no regexp expert but I was able to extract the number using basic string manipulation
var page = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var TD = "<td>";
var start = page.indexOf('Current guide price');
start = page.indexOf(TD, start);
var end = page.indexOf('</td>',start);
var number = page.substring (start + TD.length , end);
Logger.log(number);
Then, I wrote a function to convert k,m etc. to the corresponding multiplying factors.
function getMultiplyingFactor(symbol){
switch(symbol){
case 'k':
case 'K':
return 1000;
case 'm':
case 'M':
return 1000 * 1000;
case 'g':
case 'G':
return 1000 * 1000 * 1000;
default:
return 1;
}
}
Finally, tie the two together
function pullRuneScape() {
var page = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var TD = "<td>";
var start = page.indexOf('Current guide price');
start = page.indexOf(TD, start);
var end = page.indexOf('</td>',start);
var number = page.substring (start + TD.length , end);
Logger.log(number);
var numericPart = number.substring(0, number.length -1);
var multiplierSymbol = number.substring(number.length -1 , number.length);
var multiplier = getMultiplyingFactor(multiplierSymbol);
var fullNumber = multiplier == 1 ? number : numericPart * multiplier;
Logger.log(fullNumber);
}
Certainly, not the optimal way of doing things but it works.
Basically I parse the html page as you did (with corrected regex) and split the string into number part and multiplicator (k = 1000). Finally I return the extracted number. This function can be used in Google Docs.
function pullRuneScape() {
var pageContent = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var matched = pageContent.match(/Current guide price:<.th>\n<td>(\d+\.*\d*)([k]{0,1})/);
var numberAsString = matched[1];
var multiplier = "";
if (matched.length == 3) {
multiplier = matched[2];
}
number = convertNumber(numberAsString, multiplier);
return number;
}
function convertNumber(numberAsString, multiplier) {
var number = Number(numberAsString);
if (multiplier == 'k') {
number *= 1000;
}
return number;
}