Replacing certain characters with other characters - str-replace

I'm trying to set up my first discord bot to be able to replace certain letters with other letters, but I am extremely new to coding in javascript.
function debunkCommand(arguments, recievedMessage) {
if (arguments.length > 0) {
function strReplace(){
var myStr = argument;
var newStr = myStr.replace(/l/gi, "w");
var newStr = myStr.replace(/r/gi, "w");
receivedMessage.channel.send(newStr)
}
} else {
receivedMessage.channel.send("that's impossible to debunk")
}
}
expected to be able to write "!debunk hello" and have the bot send back a message saying "hewwo"

function debunkCommand(args, receivedMessage) {
if (args.length) {
/*
arguments is an array of strings, doing 'arguments.join(" ")' will join these strings into one
/[lr]+/gi will match any instances of 'l' or 'r'
it's also a good idea to rename your "arguments" parameter to "args", since "arguments" is already a standart js object
*/
receivedMessage.channel.send(args.join(" ").replace(/[lr]+/gi, "w"));
} else {
receivedMessage.channel.send("that's impossible to debunk");
};
};

Related

The operator '[]=' isn't defined for the type 'String'

I'm getting an error in this code:
void main() {
List<String> wave(String str) {
List<String> results = [];
String newStr;
int i = 0;
for (String ltr in str.split('')) {
newStr = str;
if (ltr != ' ') {
newStr[i] = ltr.toUpperCase();
results.add(newStr);
}
i++;
}
return results;
}
print(wave(' gap '));
}
the error is at the line:
newStr[i] = ltr.toUpperCase;
Despite when I try print(newStr[i]); I don't get an error and the code is executed correctly!
In Dart String operation, operator[] returns a string. Which means, array[index] is used for getting the string in the index position. That is why you're getting that error, because you can't set at specific index using this operator[] in dart. See the documentation for details.
To replace at the specific index in dart, you can use replaceFirst(Pattern from, String to, [int startIndex = 0]) as the other answer mentioned. Or, you can use substring(int start, [int? end]) as follows:
if (ltr != ' ' && i < newStr.length) {
newStr = newStr.substring(0, i) + ltr.toUpperCase() + newStr.substring(i+1);
results.add(newStr);
}
To make the code bug free, I've added the checking of the value of i in it. You should add the checking to avoid out of bound access.
try to replace
newStr[i] = ltr.toUpperCase();
to
newStr = newStr.replaceFirst(ltr,ltr.toUpperCase(),i);
So the result will be [ Gap , gAp , gaP ]
Honestly, I don't know how char is defined in Dart, but I think accessing index of String is kind of getter, thus cannot be set to a new value.

What is the best way to trim a trailing character in Dart?

In Dart the trim(), trimLeft() and trimRight() string methods do not take a parameter to specify unwanted non-whitespace characters.
What is the best way to trim a specific character from the ends of a string in Dart?
I am using this for now, but it feels hard to remember and not very generic:
final trailing = RegExp(r"/+$");
final trimmed = "test///".replaceAll(trailing, "");
assert(trimmed == "test");
There is no specific functionality to trim non-whitespace from the end of a string.
Your RegExp based approach is reasonable, but can be dangerous when the character you want to remove is meaningful in a RegExp.
I'd just make my own function:
String removeTrailing(String pattern, String from) {
if (pattern.isEmpty) return from;
var i = from.length;
while (from.startsWith(pattern, i - pattern.length)) i -= pattern.length;
return from.substring(0, i);
}
Then you can use it as:
final trimmed = removeTrailing("/", "test///")
assert(trimmed == "test");
The corresponding trimLeading function would be:
String trimLeading(String pattern, String from) {
if (pattern.isEmpty) return from;
var i = 0;
while (from.startsWith(pattern, i)) i += pattern.length;
return from.substring(i);
}
Since the existing answer by lrn has a lot of problems - including infinite loop scenarios - I thought I'd post my version.
String trimLeft(String from, String pattern){
if( (from??'').isEmpty || (pattern??'').isEmpty || pattern.length>from.length ) return from;
while( from.startsWith(pattern) ){
from = from.substring(pattern.length);
}
return from;
}
String trimRight(String from, String pattern){
if( (from??'').isEmpty || (pattern??'').isEmpty || pattern.length>from.length ) return from;
while( from.endsWith(pattern) ){
from = from.substring(0, from.length-pattern.length);
}
return from;
}
String trim(String from, String pattern){
return trimLeft(trimRight(from, pattern), pattern);
}
To trim all trailing/right characters by specified characters, use the method:
class StringUtil {
static String trimLastCharacters(String srcStr, String pattern) {
if (srcStr.length > 0) {
if (srcStr.endsWith(pattern)) {
final v = srcStr.substring(0, srcStr.length - 1 - pattern.length);
return trimLastCharacters(v, pattern);
}
return srcStr;
}
return srcStr;
}
}
For example, you want to remove all 0 behind the decimals
$23.67890000
then, invoke the method
StringUtil.trimLastCharacters("$23.67890000", "0")
finally, got the output:
$23.6789

Escaping Strings in Swift

I am going to create a CSV file programmatically and would like to properly escape my strings before writing them.
I assume I'll need to escape commas and probably need to surround each value in single or double quotes (and thus will need to escape those too). Plus any carriage return / new line constants.
I was going to write it all myself but then found this in Objective-C and said why not just convert it, as it looks quite thorough:
-(NSString *)escapeString:(NSString *)s
{
NSString * escapedString = s;
BOOL containsSeperator = !NSEqualRanges([s rangeOfString:#","], NSMakeRange(NSNotFound, 0));
BOOL containsQuotes = !NSEqualRanges([s rangeOfString:#"\""], NSMakeRange(NSNotFound, 0));
BOOL containsLineBreak = !NSEqualRanges([s rangeOfString:#"\n"], NSMakeRange(NSNotFound, 0));
if (containsQuotes) {
escapedString = [escapedString stringByReplacingOccurrencesOfString:#"\"" withString:#"\"\""];
}
if (containsSeperator || containsLineBreak) {
escapedString = [NSString stringWithFormat:#"\"%#\"", escapedString];
}
return escapedString;
}
Before I go and convert this, however, I wanted to ask the community if there is an easier way now that we're in Swift 2. Have any interesting/new changes occurred for strings that I might want to consider in favor of "Swiftifying" the above code? I did some Googling but nothing jumped out at me and I want to really make sure I do a good job here. :-)
Thanks!
You could reduce your code and save it as a String extension:
extension String {
func escapeString() -> String {
var newString = self.stringByReplacingOccurrencesOfString("\"", withString: "\"\"")
if newString.containsString(",") || newString.containsString("\n") {
newString = String(format: "\"%#\"", newString)
}
return newString
}
}
Also few tests:
var test1 = String("Test")
test1.escapeString() // produces Test
var test2 = String("Test\n")
test2.escapeString() // produces "Test\n"
var test3 = String("Test, Test2")
test3.escapeString() // produces "Test, Test2"

Find Function with RichTextBox with Labels

What I'm trying to do is to make it where the user can type in a textbox and then click on a button and it will search the richtextbox for what they are looking for and if it found something it will change the label.
(Instances)
`
Button = btn_Search
Textbox = InputBox
RichTextBox = rtb
Label = Results`
Use this method, to find any Text inside your RichTextBox.
public int FindMyText(string searchText, int searchStart, int searchEnd)
{
// Initialize the return value to false by default.
int returnValue = -1;
// Ensure that a search string and a valid starting point are specified.
if (searchText.Length > 0 && searchStart >= 0)
{
// Ensure that a valid ending value is provided.
if (searchEnd > searchStart || searchEnd == -1)
{
// Obtain the location of the search string in richTextBox1.
int indexToText = richTextBox1.Find(searchText, searchStart, searchEnd, RichTextBoxFinds.MatchCase);
// Determine whether the text was found in richTextBox1.
if(indexToText >= 0)
{
// Return the index to the specified search text.
returnValue = indexToText;
}
}
}
return returnValue;
}
call this method like this:
var res= FindMyText("hello",0. richTextBox1.Text.Length);
now if res>-1, that means positive match, then you can set your labels i.e.
if(res>-1){
lbl1.Text = "hello found";
}
source here and here
Another method of searching text that is far more clean is as below,but first you need to add
System.Text.RegularExpressions namespace to your project;
private void SearchButton_Click(object sender, EventArgs e)
{
if (textBox1.TextLength >= 1)
{
string word = textBox1.Text;//The text you want to search.
Regex searchterm = new Regex(word);//A Regular Expression is most efficient way of working with text.
MatchCollection matches = searchterm.Matches(richTextBox1.Text);
if (matches.Count >= 1)
{
Results=matches.Count.ToString();//Your label to display match instances.
richTextBox1.SelectAll();
richTextBox1.SelectionBackColor = Color.White;
richTextBox1.DeselectAll();
foreach (Match match in matches)
{
richTextBox1.Select(match.Index, match.Length);
richTextBox1.SelectionBackColor = Color.Orange;
richTextBox1.DeselectAll();
}
}
}
}
This should do the job,furthermore if you want to specify additional search options,replace the line with Regex searchterm with anyone below,
Case Insensitive
Regex searchterm = new Regex(word,RegexOptions.IgnoreCase);
Whole Word Search
Regex searchterm = new Regex(#"\b"+word+"\b");
Case Insensitive and Whole Word Search
Regex searchterm = new Regex(#"\b"+word+"\b",RegexOptions.IgnoreCase);
and one more thing,Regex searches are case-sensitive by default.

Using the Blackberry JSON parser, how do I parse out "[" from string?

I'm using the JSON library floating around for Blackberry and following this answer in "How to parse the JSON response in Blackberry/J2ME?".
The problem I'm having is that I'm getting an error saying JSONObject has to begin with a "{". My JSON string is wrapped in [ ] , which is something the web service does.
Libraries I've used for Android and iPhone stripped that, so I was wondering what is the best way around this problem? I don't think I can just parse out all [ ] because I think those are used in multidimensional JSON strings.
Edit:
Here's an example:
[{"nid":"1","title":"test","image":"m0.jpg","by":"Presented by","by_name":"Inc.","summary":"..."}, {"nid":"6","title":"A","image":".jp[0.0] g","by":"Presented by","by_name":"Theatre","summary":""}]
If you are not sure about the validity of JSON data then use any JSON Validator, e.g. JSONLint.
And you have some unwanted character in your data, i.e. [, and ] in "image":".jp[0.0] g". I think those data are added by Eclipse while printing on console.
Data provided in example isn't represent a JSONObject, butit is an array. So start with constructing a JSONArray from the data and do the parsing. Below is an example code snippet (with modified data set):
String strJSONData = "[{\"nid\":\"1\",\"title\":\"test\"},{\"nid\":\"6\",\"title\":\"A\"}]";
final String CONS_NID = "nid";
final String CONS_TITLE = "title";
try {
JSONArray ja = new JSONArray(strJSONData);
if (ja != null) {
JSONObject arrObj;
for (int i = 0; i < ja.length(); i++) {
arrObj = (JSONObject) ja.get(i);
if (arrObj.has(CONS_NID)) {
System.out.println("ID: " + arrObj.getString(CONS_NID));
}
if (arrObj.has(CONS_TITLE)) {
System.out.println("Title: " + arrObj.getString(CONS_TITLE));
}
}
arrObj = null;
}
ja = null;
} catch (Exception exc) {
}
strJSONData = null;
If you know it is starting and ending with '[' and ']', then you can just check that, and take the substring in between and hand it to the parser.
String myJsonString = ...;
if(myJsonString.charAt(0) == '[' && myJsonString.charAt(myJsonString.length() - 1) == ']') {
realJsonParse(myJsonString.substring(1, myJsonString.length() - 1);
}

Resources