golang remove characters (used for readability) in const string at compile time (spaces, \n and \t) - string

Spaces are useful to indent urls, sql queries to make it more readable.
Is there a way to remove characters from a const string at compile time in golang ?
ex: (runtime version)
const url = `https://example.com/path?
attr1=test
&attr2=test
`
// this is the code to be replaced
urlTrim := strings.Replace(
strings.Replace(url, "\n", "", -1)
)

Constant expressions cannot contain function calls (except a few built-in functions). So what you want cannot be done using a raw string literal.
If your goal with using multiple lines is just for readability, simply use multiple literals and concatenate them:
const url = "https://example.com/path?" +
"attr1=test" +
"&attr2=test"
Try it on the Go Playground.
See related question: Initialize const variable

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

Why postgres is returning additional backslash in a simple query

So in my node code postgres query is returning double quotes when it's returning its values.
As opposed to the query at pgAdmin.
I already tried to solve it using regex but this attempt was innefective. So if anyone had a problem like this and could help me, I would be glad.
Thanks in advance
There are neither quotes nor extra back slashes in the string. They are part of the string representation as literal.
Try console.log(value) - or even directly console.log('/\\w/g') - and you'll see the output is /\w/g as expected.
To answer my own question, after a lot of reading and researching, I managed to discover that because a backslash character is a special character it will create some problems around its implementation in regex, because it is not permitted to have a lone backslash stored in a variable for example.
This would never work stored inside a variable because the backslash have to be escaped.
/\w+/ig
Javascript will transform it automatically to be able to perform.
/\w+/ig
When reading
RegExp - Javascript documentation, I came across an interesting statement, the RegExp function will recognize and use a double slash regex, thankfully!
So I just adapted my regex to split it's statement from it's flags and mount it again using RegExp.
Below is the code that I used to solve this problem
// Getting values from postgres
const values = (await pgConn.admRead.query(clientQuery)).rows[0].value || [];
// Splitting regex ( values: /\w/g )
const valuesSplit = values.split('/'); // RESULT -> ['', w, g]
// Removing first array item when it's empty
if (valuesSplit[0].length === 0) {
valuesSplit.shift();
}
// Creating regex from splitted array
const regexOperation = new RegExp(valuesSplit[0], valuesSplit[1]);
// Executing replace function
const messageMasked = message.replace(regexOperation, '*');
return messageMasked;

nodejs how to replace ; with ',' to make an sql query

I have a query that looks like this:
INSERT INTO table VALUES ('47677;2019;2019;10T-1001-10010AS;A05;International;TieLineKoman-KosovoB;L_KOM-KOSB;2018;NULL;NULL;;NULL;Tieline;NULL;10XAL-KESH-----J;0;3')
that is produced by parsing a csv file.
The query is not in a valid form, I have to replace all semicolons with the string ',' (comma inside single quotes). What I want to get is:
('47677','2019','2019','10T-1001-10010AS','A05','International','TieLineKoman-KosovoB','L_KOM-KOSB','2018','NULL','NULL','','NULL','Tieline','NULL','10XAL-KESH-----J','0','3')
I have tried to do this in many different ways, but I end up with backshlashes added in my string. This is what I get:
"INSERT INTO AllocatedEICDetail VALUES ('47677\\',\\'2019\\',\\'2019\\',\\'10T-1001-10010AS\\',\\'A05\\',\\'International\\',\\'TieLineKoman-KosovoB\\',\\'L_KOM-KOSB\\',\\'2018\\',\\'NULL\\',\\'NULL\\',\\'\\',\\'NULL\\',\\'Tieline\\',\\'NULL\\',\\'10XAL-KESH-----J\\',\\'0\\',\\'3')"
Any ideas how to do this properly without having the backslashes added?
Thank you!
//the string you have
const string = '47677;2019;2019;10T-1001-10010AS;A05;International;TieLineKoman-KosovoB;L_KOM-KOSB;2018;NULL;NULL;;NULL;Tieline;NULL;10XAL-KESH-----J;0;3';
//the string you need:
const targetString = string.replace(/\;/g,',');
You specify a small regex between the forward slashes in replace which is a simple ';', give it a 'g' flag for global which will replace all instances, and in the second argument supply what you need it replaced with.

I need to read a string while ignoring any spaces or capital letters

I'm trying to read any message sent on a discord server and send a reply if a certain string is within the message ignoring all spaces and capitals. I'm very new to javascript and this is the first code I'm making just for fun.
This is the current main part of the code.
if(msg.content.toLowerCase().includes('string'))
{
msg.channel.send(emoji("480351478930866179"));
}
You can remove whitespace with replace() and shift the string to lowercase using toLowerCase() to achieve the desired result.
const original = 'Hello there.';
const str = original.replace(/\s/g, '').toLowerCase();
if (str.includes('hello')) console.log('Hi.');
You could use the string.replace method or you could use split then join. To ignore case just use toLowerCase();
Thank's, that solved my problem.
const original = 'Hello there.';
const str = original.replace(/\s/g, '').toLowerCase();
if (str.includes('hello')) console.log('Hi.');

Read and execute a file as a variable in NodeJS

I have a file and its structure is like this:
({
foo: 'bar',
bar: 'foo'
})
I'm trying to load and read the file in NodeJS so that I can get the object as a variable; what's the best way to do this? Note that I can't change the file's structure.
You could read the file into a string and eval that string:
var fs = require('fs');
var s = fs.readFileSync('myfile.js', 'utf8');
var x = eval(s);
If necessary, you could modify the string s before calling eval.
I have to agree with mtsr that a solution using JSON.parse is better (both in terms of security and probably performance as well). However, the current data file does not represent a JSON structure due to the extra parenthesis surrounding the object literal.
if you are certain that the object literal {..} is always surrounded by a (..) pair, you can remove them and then attempt to parse the string:
m = s.match(/\(([\s\S]+)\)/);
x = JSON.parse(m[1]);
The [\s\S]+ part of the regexp, matches anything including newline characters. The \( and \) part matches the surrounding parenthesis.
I would avoid eval. Try
JSON.parse()
instead.

Resources