Document document is not defined javascript in Google apps Script [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 26 days ago.
Improve this question
I can't run my code in the Google Apps Script editor. Clicking Run gives the error document is undefined.
I am trying to create a function that separates a String into substrings using a separator character and returns those substrings in an array.
function splitSrt(str, delim) {
var word = "";
var num = 0;
str = str + delim;
var x = str.length;
var substr_list = [];
for( var i = 0; i < x; i++){
if(str[i] != delim)
word = word + str[i];
else{
if(word.length != 0)
substr_list.push(word);
word = "";
}
}
return substr_list;
}
var str = "hello my world";
var delim = ' ';
var res = splitSrt(str, delim);
res.forEach(a => {
document.write( a + "<br>");
});

The code you quote will not work in Apps Script because it is attempting to write to a web page through the DOM method document.write(), which is not available in server-side code such as Node.js or Apps Script.
The problem is "function that separates a String into substrings using a passable character and returns them in an array"
You probably do not need to write a function for that. Simply use String.split(), like this:
function test() {
const str = "hello my world";
const delim = ' ';
const res = str.split(delim);
res.forEach(word => {
console.log(word);
});
}
For more complex splitting, use a regular expression as the separator.
If you really need to create your own string splitter function, start with something like this:
function splitSrt(str, delim) {
return String(str).split(delim);
}

Related

split method to return only values split by a comma not quotes in comma [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 days ago.
Improve this question
I want to split the string below by a default comma which is , and ignore the "," part.
Has anyone come up with a solution for this? Tried a bunch of solutions, but doesn't work.
My string: (testing","a framework), hello world, testing","antother_framework
expected result:
["testing","a framework", "hello world", "testing","antother_framework]
not the nicest way, with regex you could grouped the replace but it works
const str = '(testing","a framework), hello world, testing","antother_framework';
let arr = str.split(',');
console.log(arr);
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i].replaceAll('(', '');
arr[i] = arr[i].replaceAll(')', '');
arr[i] = arr[i].replaceAll('\"', '');
arr[i] = arr[i].trim();
}
console.log(arr);
You could use this function:
function splitByCommas(str) {
return str.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/);
}
Explanation:
/,(?=(?:[^"]"[^"]")[^"]$)/ -> match the comma outside of the quotes
(?:[^"]"[^"]")* -> match the quotes and the text inside the quotes
[^"]*$ -> match the remaining text after the last quote
If you run the function like this:
console.log(splitByCommas('(testing","a framework), hello world, testing","antother_framework'));
It will give the following output:
[
'(testing","a framework)',
' hello world',
' testing","antother_framework'
]
If you want to also trim the whitespaces, you can use this:
function splitByCommas(str) {
return str.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/).map(function (item) {
return item.trim();
}
);
}
For the same input giving you:
[
'(testing","a framework)',
'hello world',
'testing","antother_framework'
]

How can i extract vowels in a Javascript String? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
If i have 'var' how can i get "e,o,o" out of it ?
With substring you can only get the position
var str = "Hello world!";
var res = str.substring(1, 4);
It's not entirely clear if you only want the vowels or if you want all except the vowels. Either way, a simple regular expression can get the characters you need.
let str = "Hello World";
let res = str.match(/[aeiou]/ig).join("");
console.log(res);
let res2 = str.match(/[^aeiou]/ig).join("");
console.log(res2);
Remove the .join("") part if you want an array, otherwise this gives you a string
How about:
var str = "Hello world!";
var theGoods = str.split('').filter(c => ['e', 'o'].includes(c)).join('');
Or if you wanted the 'inverse' behavior
var str = "Hello world!";
var theGoods = str.split('').filter(c => !['e', 'o'].includes(c)).join('');
You can loop the string and store those vowels in an array.
var arr = [];
for(var i = 0; i < str.length; i++){
if(str[i] == 'e' || str[i] == 'o'){
arr.push(str[i]);
}
}
console.log(arr);}
It's pretty easy to extract them, as long as you know RegEx (regular expression)
var str = "Hello world!" // The original string
var res = str.match(/[aeiou]/gi).join("") // Extracting the vowels
// If you want to get the consonants, here you go.
var res2 = str.match(/[^aeiou]/gi).join("")
// Logging them both
console.log(res)
console.log(res2)
function deletevowels(str) {
let result = str.replace(/[aeiou]/g, '')
return result
}
var text = "Hi test of Replace Javascript";
const a = deletevowels(text);
console.log(a);

SyntaxError: Unterminated parenthetical, how to handle "( )" [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to clean up a string (anything that contains unwanted characters, diacritics, etc.) entered by a user and replace with just one string with no spaces.
I came across this error:
Execution failed: SyntaxError: Unterminated parenthetical.
It stopped at this line: idoff = accented.search(a2.charAt(i));
I was able to update our old legacy code when we encountered several accented letters (diacritics). I saw a code that I could use to resolve it but somehow I cannot figure out to how fix this one.
function clean(a2) {
/* if string contains accented letters, index below and use regular text */
var accented = 'ÁÀÂÃÄÄÅÆáàâãäåąÇçćčÐÉÉÊËèéêëðęÍÍÎÏíîïłÑñńÖÓŐÓÔÕØöóőôõøÜŰÙÚÛÜüűúûŠšŸÿýŽžŻżŁ';
var regularText = 'AAAAAAAAaaaaaaaaCcccDEEEEeeeeeeIIIIiiilNnnOOOOOOOooooooUUUUUUuuuuSSYyyZzZzL';
var idoff = -1,new_text = '';
var lentext = a2.toString().length -1
for (i = 0; i <= lentext; i++) {
idoff = accented.search(a2.charAt(i));
if (idoff == -1) {
new_text = new_text + a2.charAt(i);
} else {
new_text = new_text + regularText.charAt(idoff);
}
}
// return new_text;
/* Locate where in the string that contains ":", remove it including spaces and change string to lowercase */
var space = new_text.indexOf(":");
if (space > -1) {
var answer = new_text.substring(space);
answer = answer.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()"'+#<>?]/g,"")
answer = answer.replace(/ /g,"");
answer = answer.toLowerCase();
} else {
var answer = new_text;
answer = answer.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()"'+#<>?]/g,"")
answer = answer.replace(/ /g,"");
answer = answer.toLowerCase();
}
return answer;
}
If string is like this ABC-XYZ-LMN (AB12): XxxX Set Çompanÿ I want to clean it up to this xxxxsetcompany.
String.prototype.search expects a regular expression, but you're passing in a character (string). As you iterate over a2 you eventually come across an open parenthesis (the one surrounding "AB12"). An open parenthesis is not a valid regex.
To fix this you could use String.prototype.includes instead.
However, I think a more elegant solution to your issue may look something like this:
function clean(a2) {
/* if string contains accented letters, index below and use regular text */
const accented = 'ÁÀÂÃÄÄÅÆáàâãäåąÇçćčÐÉÉÊËèéêëðęÍÍÎÏíîïłÑñńÖÓŐÓÔÕØöóőôõøÜŰÙÚÛÜüűúûŠšŸÿýŽžŻżŁ';
const regularText = 'AAAAAAAAaaaaaaaCcccDEEEEeeeeeeIIIIiiilNnnOOOOOOOooooooUUUUUUuuuuSSYyyZzZzL'.split('');
let answer = '';
a2.split('').forEach((char) => {
let accentIndex = accented.indexOf(char);
if (accentIndex > -1) {
answer += regularText[accentIndex];
} else {
answer += char;
}
});
answer = answer.replace(/\W/gi, '');
return answer.toLowerCase();
}
console.log(clean('ABC-XYZ-LMN (AB12): XxxX Set Çompanÿ'));
Add the code after function clean(a2) {
var name = name;
name = name.replace(/[\])}[{(]/g, '');
name = name.toLowerCase();
...

Split string into even numbers forming a square [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
My objective is to split string (less than 80 characters) evenly to create a square or rectangle of strings.
var squareStr = function(str) {
}
console.log(squareStr('whatwonderfulday'));
console.log(squareStr('if life was easy god then god would not have given us brain to think'));
should output:
what
wond
erfu
lday
iflifewa
seasythe
ngodwoul
dnothave
givenusb
raintoth
ink
is this possible? I've been told I can use Math.sqrt but I'm not too sure how.
Thanks.
You can use a for loop to slice the string into the pieces and add a new line (\n) at the end of each chunk.
If you want to automatically use the square root of the string length you can do it like this:
function squareCode(string){
let squareString = "";
string = string.replace(/\s/g, '');
const splitNum = Math.floor(Math.sqrt(string.length));
for(i=0; i<= string.length; i+=splitNum){
squareString = `${squareString}${string.slice(i, i+splitNum)}\n`;
}
return squareString;
}
console.log(squareCode('whatwonderfulday'));
console.log(squareCode('if life was easy god then god would not have given us brain to think'));
console.log(squareCode('asdfasdf asdfasdfasd fasdfwe wer df gf dgdfgertqewdfsf fgdgewfwdsgewerfsd fdgdfgqefasdf'));
In the following function you'll pass in the string you want to slice as well as the number you want to slice at:
function squareCode(string, splitNum){
let squareString = "";
string = string.replace(/\s/g, '');
for(i=0; i<= string.length; i+=splitNum){
squareString = `${squareString}${string.slice(i, i+splitNum)}\n`;
}
return squareString;
}
console.log(squareCode('whatwonderfulday', 4));
console.log(squareCode('if life was easy god then god would not have given us brain to think', 8));
You could use this function. It replace all the empty spaces, then convert the string into an array and chunk it. Finally if merge every chunk and apply \n to each one.
var squareStr = function(str, chunk) {
str = str.replace(/ /g, '')
str = str.split('');
temp = []
for (i=0; i<str.length; i+=chunk)
temp.push(str.slice(i,i+chunk));
return temp.map(function(a){return a.join('')+"\n"}).join('')
}
console.log(squareStr('whatwonderfulday', 4));
console.log(squareStr('if life was easy god then god would not have given us brain to think', 8));
So many ways of doing that...
All other answers here are correct too, here's my approach, a more "readable" answer, using very basic recurses...
You have should at least tried...
I also have included a check to see if the string lenght is under 80.
var squareStr = function(str, charsPerLine) {
if (str.length > 80){
return;
}
str = str.replace(/ /g,'')
var stringSplited = str.split('');
var newString = '';
stringSplited.forEach(function(letter,index){
if (index % charsPerLine == 0 && newString.length > 0){
newString += '\n'; //IF YOU WANT TO USE IT IN THE HTML, USE '<br>' HERE
}
newString += letter;
});
console.log(newString);
return newString;
}
squareStr('whatwonderfulday', 4);
squareStr('if life was easy god then god would not have given us brain to think', 8);
Unless you're dealing with really long strings, I don't see a reason not to use replace to insert a newline every n characters:
function squareText(input) {
const inputNoSpaces = input.replace(/\s/g, '');
const partLen = Math.ceil(Math.sqrt(inputNoSpaces.length));
const replaceExpr = new RegExp(`.{1,${partLen}}`, 'g');
return inputNoSpaces.replace(replaceExpr, '$&\n');
}
const input = 'if life was easy then god would not have given us brain to think';
console.log(squareText(input));
This just calculates the line length and then creates a new RegExp that matches that many characters and uses it to replace each match with itself plus a newline.

How to remove the blank lines in a textarea with JavaScript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I get the content of a textarea with:
var stringArray = document.getElementById('textarea').value;
I must remove all blank lines (even blank lines with spaces). What is an efficient way to do that?
EDIT: I want to remove the blank lines, not the whitespace.
e.g.
A
B
C
D
to
A
B
C
D
Finally I managed to make it work. This is the code just in case someone else would need it:
function delBlankLines() {
var stringArray = document.getElementById('textarea').value.split('\n');
var temp = [""];
var x = 0;
for (var i = 0; i < stringArray.length; i++) {
if (stringArray[i].trim() != "") {
temp[x] = stringArray[i];
x++;
}
}
temp = temp.join('\n');
document.myform.textarea.value = temp;
}
So, the textarea content is split into a string array, that array is looped and checked if the trimmed current line is blank; if it's not, the line is copied to a temporary string array (basically the blank lines are ignored). At the end, I update the textarea with the temporary string array.
you can use the native JavaScript trim method (available on the string prototype): textareaValue.trim().
Trivia: there's automatic setting of window.textarea to be document.getElementById('textarea'). So you can access that by just doing textarea. Therefore to access the textual content of the textarea you can use: textarea.innerHTML or const textAreaValue = textarea.value.
Next, run textAreaValue.trim(); this will get rid of any outer white space. " \n\n textArea \n\n\t\n " will turn into just "textArea".
Ok now we can split on new lines: const stringArray = textAreaValue.split('\n'). Since \n is the carriage return aka new line symbol.
Next, we'll want to skip any lines which have nothing but whitespace which we can probably find in a few ways but to be safest \S should work. To test out different regexes I recommend: regex101.com.
For a more modern version:
textarea.value = `
the
quick
brown
fox
jumped
over the lazy
dog.
`;
/*
function oldSolution() {
var cleanedString = '';
console.log(textarea.value);
var stringArray = textarea.value.trim().split('\n');
for(var i = 0; i < stringArray.length; i++){
var line = stringArray[i];
if(line.match('/\S/') !== -1){
cleanedString += line.trim();
}
}
console.log(cleanedString);
output.innerText = cleanedString;
return cleanedString;
}
*/
const cleanText = () => {
const stringArray = textarea.value
.trim()
.split('\n')
.filter(line => /\S/.test(line));
console.log({stringArray})
const cleanedString = stringArray.map(line => line.trim()).join(' ');
console.log(cleanedString);
output.innerText = cleanedString;
return cleanedString;
}
<textarea rows='5' cols='50' id='textarea'></textarea>
<input type='button' value='Extract Text' onclick='cleanText()'/>
<div id="output"></div>

Categories

Resources