How to escape string and JSON.stringify - node.js

I'm trying to serve API with nodeJS, and database use oracle. I've an object like this that I got from req.body.detail:
{
title: "How to Have",
content: "<ol><li><b>Lorem ipsum dolor sit amet.</b></li></ol>"
}
then I do
const data = JSON.stringify(req.body.detail);
but the inserted data in table become doesn't has escape string, it become likes:
{"title":"How to Have","content":"<ol><li><b>Lorem ipsum dolor sit amet.</b></li></ol>}
How do I can escape string to whole object and result become like this:
{"title":"How to Have","content":"<ol><li><b>Lorem ipsum dolor sit amet.<\/b><\/li><\/ol>}
My column in table has datatype clob.

To escape these / characters with \, use String.replace():
const escapedString = inputString.replace(/\//g, '\\/')
The first parameter is a regex. Its g qualifier means match all instances, not just the first. \/ means match the / character, which must be replaced in a regex, because ....
regexes themselves start and end with /. Hence /\//g .
And the replacement string literal is \\/ because you must escape \ to put it into a string literal: \\/ written in your program gets you the value \/.
But Oracle doesn't require you to escape these characters before you jam them into a clob. So that must be a requirement from the software that will read that clob.

Use the JSON.stringify() function like this for indents:
const data = JSON.stringify(req.body.detail, null, 4);
What I think most people don't know is that JSON.stringify() accepts three parameters: first one is the JSON data, second is a function, and third is a number based on how many spaces you want the data to be indented by. Here's the MDN documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

In general, don't escape data on insert into a DB. You should filter data on INSERT (to check it is valid), and escape data on SELECT. It is only when you select the data that the app (or future apps) know where the data will be used. Some apps won't want escaped data.

Related

Adding and trimming spaces before and after separator

If string contain text with one single special character (separator),
How to ad a space after point before separator and trim any space after separator?
Exemple string:
.Dolo.rum ipsum primos# ar.deo
J.ust. simple text# h er.e
Another fr.e.e #. exe mpl e
Expect result:
. Dolo. rum ipsum primos#ar.deo
J. ust. simple text#her.e
Another fr. e. e #.exemple
Since an accepted answer can't be deleted hence sharing the solution as mentioned in the first comment,
=SUBSTITUTE(LEFT(A1,FIND("#",A1)),".",". ")&SUBSTITUTE(MID(A1,FIND("#",A1)+1,LEN(A1))," ","")

How to remove whitespace from a string in Rascal?

When you have a string in Rascal like this:
"\n\tThis is a specification of a toy Transaction.\n\tVia a transaction money
can be transfered between two accounts\n"
Or
This is a specification of a toy Transaction.
Via a transaction money can be transfered between two accounts
How can I remove the whitespace in the middle of the string?
My solution now is to call a function that replaces '\n', '\t', and '\r' but this doesn't seem like a sustainable solution. Also, the function trim only remove whitespace at the beginning and end.
visit (x) {
case /[\t\n]/ => ""
}

Display the specific part of the string in PostgreSQL 9.3

I have a string to modify as per the requirements.
For example:
The given string is:
str1 varchar = '123,456,789';
I want to show the string as:
'456,789'
Note: The first part (delimited) with comma, I want to remove from string and show the rest of string.
In SQL Server I used STUFF() function.
SELECT STUFF('123,456,789',1,4,'');
Result:
456,789
Question: Is there any string function in PostgreSQL 9.3 version to do the same job?
you can use regular expressions:
select substring('123,456,789' from ',(.*)$');
The comma matches the first comma found in the string. The part inside the brackets (.*) is returned from the function. The symbol $ means the end of the string.
A alternative solution without regular expressions:
select str, substring(str from position(',' in str)+1 for length(str)) from
(select '123,456,789'::text as str) as foo;
You could first turn the string to array and return second and third cell:
select array_to_string((regexp_split_to_array('123,456,789', ','))[2:3], ',')
Or you could use substring-function with regular expressions (pattern matching):
SELECT substring('123,456,789' from '[0-9]+,([0-9]+,[0-9]+)')
[0-9]+ means one or more digits
parentheses tell to return that part from the string
Both solutions work on your specific string.
Your The SQL Server example indicates you just want to remove the first 4 characters, which makes the rest of your question seem misleading because it completely ignores what's in the string. Only the positions matters.
Be that as it may, the simple and cheap way to cut off leading characters is with right():
SELECT right('123,456,789', -4);
SQL Fiddle.

Reading from a string using sscanf in Matlab

I'm trying to read a string in a specific format
RealSociedad
this is one example of string and what I want to extract is the name of the team.
I've tried something like this,
houseteam = sscanf(str, '%s');
but it does not work, why?
You can use regexprep like you did in your post above to do this for you. Even though your post says to use sscanf and from the comments in your post, you'd like to see this done using regexprep. You would have to do this using two nested regexprep calls, and you can retrieve the team name (i.e. RealSociedad) like so, given that str is in the format that you have provided:
str = 'RealSociedad';
houseteam = regexprep(regexprep(str, '^<a(.*)">', ''), '</a>$', '')
This looks very intimidating, but let's break this up. First, look at this statement:
regexprep(str, '^<a(.*)">', '')
How regexprep works is you specify the string you want to analyze, the pattern you are searching for, then what you want to replace this pattern with. The pattern we are looking for is:
^<a(.*)">
This says you are looking for patterns where the beginning of the string starts with a a<. After this, the (.*)"> is performing a greedy evaluation. This is saying that we want to find the longest sequence of characters until we reach the characters of ">. As such, what the regular expression will match is the following string:
<ahref="/teams/spain/real-sociedad-de-futbol/2028/">
We then replace this with a blank string. As such, the output of the first regexprep call will be this:
RealSociedad</a>
We want to get rid of the </a> string, and so we would make another regexprep call where we look for the </a> at the end of the string, then replace this with the blank string yet again. The pattern you are looking for is thus:
</a>$
The dollar sign ($) symbolizes that this pattern should appear at the end of the string. If we find such a pattern, we will replace it with the blank string. Therefore, what we get in the end is:
RealSociedad
Found a solution. So, %s stops when it finds a space.
str = regexprep(str, '<', ' <');
str = regexprep(str, '>', '> ');
houseteam = sscanf(str, '%*s %s %*s');
This will create a space between my desired string.

How to make work newline inside c-string returned by a sqlite3 text column?

I'd like to know how to make work newline control character inside c-string returned by a sqlite3_column_text. For example, this is the text returned from a query to a sqlite database:
"Lorem ipsum\ndolor sit amet,\nconsectetur\nadipiscing elit."
and this is the code I use to get it:
char *body = (char *)sqlite3_column_text(statement, 1);
NSString *str = (body)?[NSString stringWithUTF8String:body]:#"";
The problem comes when I try to print it, because in return this:
Lorem ipsum\ndolor sit amet,\nconsectetur\nadipiscing elit.
instead of:
Lorem ipsum
dolor sit amet,
consectetur
adipiscing elit.
Using the same text but returned from a string column in Core Data works as intended, but I don't know why is doesn't in sqlite3. I hope someone can give directions because is quite frustrating.
Looking in the literal values section of the documentation of SQLite I found that the reason of why it return the two-character \n instead of newline is because C-style escapes using the backslash character are not supported because they are not standard SQL. So I tried a different aproach by using NSString instead of using SQLite directly:
char *body = (char *)sqlite3_column_text(statement, 1);
NSString *str = (body)?[NSString stringWithUTF8String:body]:#"";
NSString *container = [str stringByReplacingOccurrencesOfString:#"\\n"
withString:#"\n"];
Thanks to this two posts, I get the idea of using \\n to replace \n correctly in the final NSString, so is possible to use other valid control characters.
The issue is that the value stored in the sqllite DB is the two-character \n and not the newline itself. You will have to either convert the \n into the newline (ASCII 10) character before adding the string to the DB or process the string after the SELECT query in your Objective-C code.
See the following answers for further info:
Trouble with newline character while programming for the iPhone
Preventing sqlite from escaping backslash

Resources