search and replace multiple words in AS3 - string

I've got this code in my AS3 :
var str:String = mySharedObject.data.theDate;
var search:String = "monday";
var replace:String = "";
function strReplace(str:String, search:String, replace:String):String {
return str.split(search).join(replace);
}
Is it possible to tell the code to search for "monday or tuesday or wednsday, or thursday, or friday" and replace them with "_" ?
And, secondly, is it possible to tell the code to search for "January" and replaced it by "01", "February" by "02"...etc ? (in one line if it's possible) ?
Thx
EDIT
I'd like to do something as simple as that :
str.replace( "monday"||"tuesday"||"wednsday" , "" );
Or
var search:String ="tuesday","wednsday","thursday";
But it's not working..

What you want is a regular expression which is implemented in the RegExp class in AS3. The pattern passed into String.replace() can be a RegExp which can be used to do type of matching you want.
A simple regular expression to match English language work days could look like this:
(Monday|Tuesday|Wednesday|Thursday|Friday)
which is Regular Expression for "match Monday or Tuesday or Wednesday or Thursday or Friday". Note that this almost certainly isn't the best regex for this but it's simple and it works. There's a link where you can learn more about regexes at the bottom of this answer.
This regex can be put into a function that takes the string to search, the string to replace matches with and a string called flag. flag is a list of options that modify how the regex works. The docs for the RegExp construction provide complete details. This function might look like:
private function replaceDay(str:String, replace:String, flag:String = ''):String
{
var search:RegExp = new RegExp("(Monday|Tuesday|Wednesday|Thursday|Friday)", flag);
return str.replace(search, replace);
}
You can then test it out (I've run it all in Flash Builder successfully):
// Replace a single, normally capitalized day name
var monday:String = "Monday the 1st";
trace(replaceDay(monday, "REDACTED")); // REDACTED the 1st
// Replace multiple normally capitalized day names
var mondayAndTuesday:String = "Either Monday or Tuesday works for me";
trace(replaceDay(mondayAndTuesday, "", "g")); // Either or works for me
// Replace a single day name regardless of capitalization
var lowerCaseWednesday:String = "wednesday";
trace(replaceDay(lowerCaseWednesday, "yadsendew", "i")); // yadsendew
var weirdCaseThursday:String = "tHurSdaY";
trace(replaceDay(weirdCaseThursday, "It's actually 'Thursday'.", "i")); // It's actually 'Thursday'.
// Replace multiple day names regardless of capitalization
var friday:String = "FriDAY FRIDAY friday";
trace(replaceDay(friday, "Something", "ig")); // Something Something Something
As for your question about replacing month names with numbers that is possible as well. The last example in the docs for String.replace() shows how to use a function as the replace value. Since StackOverflow prefers one post, one question you should remove it from this post and post another question.
For more info on regular expressions check out http://www.regular-expressions.info/

Related

App Script - Google Sheets - basics of working with strings

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

How to avoid google translate to translate :parameters

I'm using a library nikaia/translation-sheet who basically pulls all the translations from the Laravel site into a google spreadsheet making it "easily" translatable with =GOOGLETRANSLATE(A1)
The problem comes with the parameters:
:price
:amount
:etc
So I've got the idea to substitute ":" with #nonmakingsenseworblablaprice so Google couldn't translate example:
=SUBSTITUTE(GOOGLETRANSLATE(SUBSTITUTE(B2;":";"#nonmakingsenseworblabla");"ES";"EU");"#nonmakingsenseworblabla";":")
Well, not sure why Google eats some letters and puts new ones:
:amount de saldo -> #nonmakingseseworblatamount of saldo
So I decided to do something like detect the parameter and change :amount to :a_m_o_u_n_t and that is apparently working and not being weirdly parsed converted or translated.
I was looking for a solution and found a similar idea but having problems migrating it to spreadsheets script plus is not detecting the parameter
Any one knows how to detect all :parameters in a sentence and put a symbol, slash, dash etc between the characters or letters? Example:
The amount :amount for this order number :order_id is :price
I've also tried regex but not been lucky so far
=REGEXREPLACE(GOOGLETRANSLATE(REGEXREPLACE(B22; ":(\w)([\w]+)"; "{%$1_$2%}"); "ES"; $C$1); "{%(\w)_([^_]+)%}"; ":$1$2")
There's a regex to select the spaces between letters, but good luck making that in excel or spreadsheets. Demo
Finally I've created a script to avoid parameters translation:
function translate(cell, lang) {
const content = cell.toString();
const keys = [];
const enc = content.replace(/:([\w_]+)/ig, function(m, param) {
const n = `[§${keys.length}]`;
keys.push(param);
return n;
});
return LanguageApp.translate(enc, "es", lang).replace(/\[§(\d+)\]/ig, function(m, param) {
return `:${keys[param]}`;
});

Find and replace text and wrap in "href"

I am trying to find specific word in a div (id="Test") that starts with "a04" (no case). I can find and replace the words found. But I am unable to correctly use the word found in a "href" link.
I am trying the following working code that correctly identifies my search criteria. My current code is working as expected but I would like help as i do not know how to used the found work as the url id?
var test = document.getElementById("test").innerHTML
function replacetxt(){
var str_rep = document.getElementById("test").innerHTML.replace(/a04(\w)+/g,'TEST');
var temp = str_rep;
//alert(temp);
document.getElementById("test").innerHTML = temp;
}
I would like to wrap the found word in an href but i do not know how to use the found word as the url id (url.com?id=found word).
Can someone help point out how to reference the found work please?
Thanks
If you want to use your pattern with the capturing group, you could move the quantifier + inside the group or else you would only get the value of the last iteration.
\ba04(\w+)
\b word boundary to prevent the match being part of a longer word
a04 Match literally
(\w+) Capture group 1, match 1+ times a word character
Regex demo
Then you could use the first capturing group in the replacement by referring to it with $1
If the string is a04word, you would capture word in group 1.
Your code might look like:
function replacetxt(){
var elm = document.getElementById("test");
if (elm) {
elm.innerHTML = elm.innerHTML.replace(/\ba04(\w+)/g,'TEST');
}
}
replacetxt();
<div id="test">This is text a04word more text here</div>
Note that you don't have to create extra variables like var temp = str_rep;

Code about replacing certain words in discord.js

I was trying to make the bot replace multiple words in one sentence with another word.
ex: User will say "Today is a great day"
and the bot shall answer "Today is a bad night"
the words "great" and "day" were replaced by the words "bad" and "night" in this example.
I've been searching in order to find a similar code, but unfortunately all I could find is "word-blacklisting" scripts.
//I tried to do some coding with it but I am not an expert with node.js the code is written really badly. It's not even worth showing really.
The user will say some sentence and the bot will recognize some predetermined words on the sentence and will replace those words with other words I'll decide in the script
We can use String.replace() combined with Regular Expressions to match and replace single words of your choosing.
Consider this example:
function antonyms(string) {
return string
.replace(/(?<![A-Z])terrible(?![A-Z])/gi, 'great')
.replace(/(?<![A-Z])today(?![A-Z])/gi, 'tonight')
.replace(/(?<![A-Z])day(?![A-Z])/gi, 'night');
}
const original = 'Today is a tErRiBlE day.';
console.log(original);
const altered = antonyms(original);
console.log(altered);
const testStr = 'Daylight is approaching.'; // Note that this contains 'day' *within* a word.
const testRes = antonyms(testStr); // The lookarounds in the regex prevent replacement.
console.log(testRes); // If this isn't the desired behavior, you can remove them.

Go how can i efficient split string into parts

i am fighting with a string splitting. I want to split string by wildcards into a slice, but this slice should contain this wildcards as well.
For example: /applications/{name}/tokens/{name} should be split into [/applications/ {name} /tokens/ {name}] etc.
Here is a sample code i wrote, but it is not working correctly, and i don't feel good about it either.
https://play.golang.org/p/VMOsJeaI4l
There are some example routes to be tested. Method splitPath split path into parts and display both: before and after.
Here is a solution:
var validPathRe = regexp.MustCompile("^(/{[[:alpha:]]+}|/[-_.[:alnum:]]+)+$")
var splitPathRe = regexp.MustCompile("({[[:alpha:]]+}|[-_.[:alnum:]]+)")
func splitPath(path string) parts{
var retPaths parts
if !validPathRe.MatchString(path) {
return retPaths
}
retPaths = splitPathRe.FindAllString(path, -1)
return retPaths
}
I made this by creating two regular expressions, one to check if the path was valid or not, the other to extract the various parts of the path and return them. If the path is not valid it will return an empty list. The return of this will look like this:
splitPath("/path/{to}/your/file.txt")
["path" "{to}" "your" "file.txt"]
This doesn't include the '/' character because you already know that all strings in the return but the last string is a directory and the last string is the file name. Because of the validity check you can assume this.

Resources