App Script - Google Sheets - basics of working with strings - string

First time posting here. I'm an experienced coding, but it's been a long time since I've done any, and I'm starting back up with App Script, a new language for me. I'm trying to do some basic stuff with text found within cells in a Google sheets. I've gotten it to work well enough, but I think my code can be simplified and improved if I learn a little bit more about working with text strings in App Script.
This is a very simplified version of my function. My real function finds the page numbers given in a citation in one cell, and puts just those page numbers in another cell. For the purposes of this question, I've simplified it to retrieve the text from the current cell, remove the first blank space in the text, count the numbers at the beginning of the text, and then write just those numbers into the current cell. It does what it is supposed to do, and what I need it to do, but I have so many questions! Thank you!!
function myFunction() {
var spreadsheet = SpreadsheetApp.getActive(); var
currentCell = spreadsheet.getCurrentCell().activate();
var style = SpreadsheetApp.newTextStyle().setForegroundColor('#000000').build();
var textString = currentCell.getRichTextValue().getText();
var count = 0;
var char = textString.substring(count,count+1);
textString = textString.replace(" ","");
while(char<10)
{
count = count+1;
char = textString.substring(count,count+1);
}
var numbers = textString.substring(0,count);
currentCell.setRichTextValue(SpreadsheetApp.newRichTextValue().setText(numbers)
.setTextStyle(1, count, style).build());
};
In retrieving my textString, is there a way to do it without using "getRichTextValue()"?
In writing the new text (numbers), is there a way to do that without using "setRichTextValue()"? And to do it without specifying the style?
In my while loop, I use char<10. This works, but I'm not sure why. char is a one character string, right? The character is a number, but I am thinking I shouldn't be able to compare with a number because it's a string? Also, it actually lets blank spaces through as well, so I know something is wrong. What can I do instead?
How can I get the replace function to remove ALL the blank spaces in my textString?

Here is a modified version of your script using Regex.
The reason your code char<10 works is it is comparing the ASCII value of the character with A being 10 and 0 to 9 being ASCII value 0 to 9.
function myFunction() {
var spreadsheet = SpreadsheetApp.getActive();
var currentCell = spreadsheet.getCurrentCell(); // returns a range, no need to activate
var textString = currentCell.getValue();
// use reges to remove all blank spaced
textString = textString.replace(/\s/g,"");
// use regex to get the first string of digits
// match returns an array so we need the first element of the array
var numbers = textString.match(/\d+/)[0];
currentCell.setValue(numbers)
}
Reference
Range.getValue()
Range.setValue()
Regex tester

Related

How to remove all punctuation from a string in Godot?

I'm building a command parser and I've successfully managed to split strings into separate words and get it all working, but the one thing I'm a bit stumped at is how to remove all punctuation from the string. Users will input characters like , . ! ? often, but with those characters there, it doesn't recognize the word, so any punctuation will need to be removed.
So far I've tested this:
func process_command(_input: String) -> String:
var words:Array = _input.replace("?", "").to_lower().split(" ", false)
It works fine and successfully removes question marks, but I want it to remove all punctuation. Hoping this will be a simple thing to solve! I'm new to Godot so still learning how a lot of the stuff works in it.
You could remove an unwantes character by putting them in an array and then do what you already are doing:
var str_result = input
var unwanted_chars = [".",",",":","?" ] #and so on
for c in unwanted_chars:
str_result = str_result.replace(c,"")
I am not sure what you want to achieve in the long run, but parsing strings can be easier with the use of regular expressions. So if you want to search strings for apecific patterns you should look into this:
regex
Given some input, which I'll just write here as example:
var input := "Hello, It's me!!"
We want to get a modified version where we have filtered the characters:
var output := ""
We need to know what we will filter. For example:
var deny_list := [",", "!"]
We could have a list of things we accept instead, you would just flip a conditional later on.
And then we can iterate over the string, for each character decide if we want to keep it, and if so add it to the output:
for position in input.length():
var current_character := input[position]
if not deny_list.has(current_character):
output += current_character

How to remove string after and before specific chars

I have this string: https://2352353252142dsbxcs35#github.com/happy.git
I want to get result: https://github.com/happy.git (without random string after second / and after # but without #).
Now I have something like this:
var s = 'https://2352353252142dsbxcs35#github.com/happy.git';
var d = s.substring(s.indexOf('/')+2, s.indexOf('#')+1;
s = s.replace(d, "");
it works, but I know it's an ugly solution.
What is the most efficient and more universal solution?
Try this:
const indexOfAtSign: number = receivedMessage.indexOf('#')+1
const httpsString: string = 'https://'
const trimmedString: string = s.slice(indexOfAtSign)
const requiredURL: string = httpsString.concat(trimmedString)
// Print this value of requiredURL wherever you want.
So here what my code does is, it gets position of # and removes everything before it along with the sign itself. Then using the slice() function, we are left with the remaining part which I named as trimmedString. Now I have pre-defined the `https string, anf we just need to merge them now. Done :-)
I had tried this out in my telegram bot and here's how it works:

Ampscript BuildRowsetFromString() fails on single item

I've been tasked with an ExactTarget task, which uses Ampscript. Trying to learn on the go here. See code snippet below:
%%[
Var #testString, #testOutput
Set #testString = Qwerty
Set #testOutput = BuildRowsetFromString(#testString,"~")
]%%
TestOutput:%%= v(#testOutput) =%%
The code works if the testString contains a ~, but when there is no ~ character in the string, the ouput is blank. Is this correct by design? Do I need to add a conditional to check for the presence of the ~ character?
That's the expected behavior. The BuildRowsetFromString() function alone isn't going to return any value when displayed, you're going to need to use Row() and Field() in order to pull the value out.
Using your example:
%%[
Var #testString, #testOutput
Set #testString = "Qwerty"
Set #testOutput = BuildRowsetFromString(#testString,"~")
]%%
RowCount: %%=RowCount(#testOutput)=%%
TestOutput: %%=v(#testOutput)=%%
The RowCount() function returns a value of 1, essentially saying it knows there's at least one 'row' in there. To display that one value, you'll need to wrap that value with Field() and Row():
TestOutput: %%=Field(Row(#testOutput,1),1)=%%
If you want to display other values in the string, say you were passing "Qwerty~Second~Third", you'll need to either change the number at the Row() function or perform a loop.
References
Using Loops
BuildRowsetFromString() Function

Dynamic Strings, AS2, needed on one line

Ok, so I'm creating a Flash HUD in AS2 that runs on the Surface and connects to our server.
As it stands now, I'm having to hard code the IP addresses for the Surface to connect to, and I'm trying to get past this.
I have 4 text fields for the user to enter the 4 fields of IP address data. My issue at the moment is that if I set the String variable literally, it works fine. But if I dynamically create the string, instead of outputting on one line, it outputs each of the 4 strings separately.
Here's my code:
var newIP1 = getIP.IPtext.IP1.text; //grabbing the data from the UI
var newIP2 = getIP.IPtext.IP2.text;
var newIP3 = getIP.IPtext.IP3.text;
var newIP4 = getIP.IPtext.IP4.text;
var ipArray = new Array(newIP1,newIP2,newIP3,newIP4); //setting the array
trace (ipArray.join(".")); // output the string, replacing the commas with a period
//output:
//10
//.255
//.255
//.22
//If I do this it works fine
var IPstr = "10.255.255.2";
trace(IPstr);
// output: 10.255.255.22
I appreciate any help on this, thanks in advance.
Your code looks good and should work as expected.
One thing to check would be to see if there isn't a carriage return or newline character being added to each individual input box. One way to check would be to check the length of each of your input strings to ensure there isn't an invisible character there.

Is there any way to retrieve a appended int value to a String in javaScript?

I am currently working on a project that dynamically displays DB content into table.
To edit the table contents i am want to use the dynamically created "string"+id value.
Is there any way to retrieve the appended int value from the whole string in javaScript?
Any suggestions would be appreciative...
Thanks!!!
If you know that the string part is only going to consist of letters or non-numeric characters, you could use a regular expression:
var str = "something123"
var id = str.replace(/^[^\d]+/i, "");
If it can consist of numbers as well, then things get complicated unless you can ensure that string always ends with a non-numeric character. In which case, you can do something like this:
var str = "something123"
var id = str.match(/\d+$/) ? str.match(/\d+$/)[0] : "";
(''+string.match(/\d+/) || '')
Explanation: match all digits in the variable string, and make a string from it (''+).
If there is no match, it would return null, but thanks to || '', it will always be a string.
You might try using the regex:
/\d+$/
to retrieve the appended number

Resources