Why html escape /? - html

I was looking at this answer (copied below)
What I didn't understand is why is / escaped?
There is also the solution from mustache.js
https://github.com/janl/mustache.js/blob/master/mustache.js#L82
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}

There is no need at all to escape the / in HTML.

Related

What does sky-scrapper mean?

In this answer there is a Prolog predicate with the comment
% replace OR sky-scrapper with call to new predicate
Googling has no results for the first few pages that I see to explain its meaning.
What is the meaning and origin of sky-scrapper as used in the comment?
In the example code in link, the OP has used below style
( ":", !, { Token = tokColon }
; "(", !, { Token = tokLParen }
; ")", !, { Token = tokRParen }
; "{", !, { Token = tokLMusta}
; "}", !, { Token = tokRMusta}
; "\\", !, { Token = tokSlash}
; "->", !, { Token = tokImpl}
; "+", !, { Token = tokPlus }
; "-", !, { Token = tokMinus }
; "*", !, { Token = tokTimes }
; "=", !, { Token = tokEqual }
; "<", !, { Token = tokLt }
; ">", !, { Token = tokGt }
; "_", !, { Token = tokUnderscore }
; ".", !, { Token = tokPeriod }
; "/", !, { Token = tokForwardSlash }
; ",", !, { Token = tokComma }
; ";", !, { Token = tokSemicolon }
this snippet is long(tall) like sky scraper, and thats why terminology is used IMHO
and so OP is suggested to replace it
with a more proper snippet, this are mostly to produce more readable and maintainable code
I think it's a typo for "skyscraper". The code example is probably solving a skyscraper puzzle.
Optimizing pathfinding in Constraint Logic Programming with Prolog

To replace enter key press event with \n

textarea.html
<textarea [(ngModel)]="array" (keypress)="onKeypress($event)"></textarea>
<div>
<p>{{array}}</p>
</div>
textarea.ts
rray:any;
constructor() {
this.array =["test1", "test2", "test3"];
// let array2 = ((array).toString()).split("");
// let array3 = array.join("textarea");
}
ngOnInit() {
}
onKeypress(event){
if (event.key == "Enter"){
this.array = this.array + "\n";
return false;
}
else{
return true;
}
}
}
How to print "\n" when enter key is pressed in the textarea using angular 5? The above code does not work.
actually the error was that I had use "/\n" instead of "\n" as \n is a special character. After doing this it worked
If your code compiles well, then consider adding escape character to show the new line character inline with your textbox area. So instead of "\n" use "\\n".
Here is the working example.

Converting JSON data to CSV in Cloudant using List and View

I tried to convert the JSON data in my Cloudant db to csv format, using the List function. It works perfectly for all values except JSON array values, i.e. the nested values. For these, I am getting [object object] as the output in my csv document.
Please find the sample JSON document which I am using, below:
{
"NAME": "Aparna",
"EMAIL": "something#domain.com",
"PUBLIC_OFFICIALS_CONTACTED": [
{ "NAME_PUBLIC_OFFICIAL": [ "ab"],
"TITLE_PUBLIC_OFFICIAL": ["cd"]}
],
"COMMUNICATION_TYPE": [
"Meeting",
"Phone",
"Handout",
"Conference"
],
"NAMES_OF_OTHERS_FROM_IBM": [
{ "NAME_OF_OTHERS": ["ef"],
"TITLE_OF_OTHERS": [ "gh"]}
],
"COMMUNICATION_BENEFIT": "Yes",
"LAST_UPDATE_BY" : "ap"
}
Please find the map and list functions used below :
"map" : "function(doc){
if((\"SAVE_TYPE_SUBMIT\" in doc) && (doc.SAVE_TYPE_SUBMIT== \"Submit\")) {
emit (doc. LAST_UPDATE_BY,[doc.NAME,doc.EMAIL,doc.PUBLIC_OFFICIALS_CONTACTED[0].NAME_PUBLIC_OFFICIAL,\n doc.PUBLIC_OFFICIALS_CONTACTED[0].TITLE_PUBLIC_OFFICIAL,doc.COMMUNICATION_TYPE,doc.NAMES_OF_OTHERS_FROM_IBM[0].NAME_OF_OTHERS, doc.NAMES_OF_OTHERS_FROM_IBM[0].TITLE_OF_OTHERS, doc.COMMUNICATION_BENEFIT,doc. LAST_UPDATE_BY,doc.LAST_UPDATE_DATE]) ;
}
}
"list" : "function (head, req) {
var row;
start({\n headers: {'Content-Type': 'text/csv' },
});
var first = true;
while(row = getRow()) {
var doc = row.doc;
if (first) {
send(Object.keys(doc).join(',') + '\\n');
first = false;\n }
var line = '';
for(var i in doc) {
// comma separator
if (line.length > 0) {
line += ',';\n }
// output the value, ensuring values that themselves
// contain commas are enclosed in double quotes
var val = doc[i];
if (typeof val == 'string' && val.indexOf(',') > -1) {
line += '\"' + val.replace(/\"/g,'\"\"') + '\"';
}
else {
line += val;
}
}
line += '\\n';
send(line);
}}"
Note : In the map, only the first values have been fetched from the JSON arrays for now, on purpose, to simplify the function.
Please help understand how to fetched the nested JSON values or arrays and download the same in csv format. Any guidance would be much appreciated!
You can try to stringify the object you are trying to export and you will get some clue
if (typeof val == 'string' && val.indexOf(',') > -1) {
line += '\"' + val.replace(/\"/g,'\"\"') + '\"';
}
else {
line += JSON.stringify(val);
}
Or even better
if (typeof val == 'string' && val.indexOf(',') > -1) {
line += '\"' + val.replace(/\"/g,'\"\"') + '\"';
}
else if(val instanceof Array){
line += val.join(',');
}
else {
line += JSON.stringify(val);
}
There are a couple of things to change here that might help. The first thing is that you don't need to emit all the values you want to use, because you can access the document itself from the list when dealing with a view.
With this in mind, the map could have an emit like
emit (doc.LAST_UPDATE_BY, null);
With this in place, if you request the list/view with include_docs=true then you can refer to the fields in your document inside the while(row = getRow()) section like this:
send(row.doc.NAME + ',' + row.doc.EMAIL + '\\n');
And for the nested documents, try something like:
row.doc.PUBLIC_OFFICIALS_CONTACTED.0.NAME_PUBLIC_OFFICIAL
You already referred in another question to the article I'd recommend for a full working example https://developer.ibm.com/clouddataservices/2015/09/22/export-cloudant-json-as-csv-rss-or-ical/ - hopefully this explanation helps also.

Json Parse Unexpected token with node

I am getting a strange unexpected token error trying to parse a JSON file using node. I have tested the code with 2 files that look identical. I used a code compare tool to do a comparison and they do appear identical. However, when I try to parse them, one gets the error and the other does not. The file that does not work is being generated from a PowerShell script. The one that does work was manually created. I am baffled. One thing I noticed that is different about them when I write the json out to the console is, the one that does not work has a ? at the beginning.
The json from the file that does not work:
data = ?{ "stack_name": "perf-a", "parameters": { "StackSet": "b", "MonitoringEnableAutoscalingAlarm": "True", "MachineConfigEnvironment": "Perf", "AppEnvironmentType": "perf", "StackInRotation": "True", "MonitoringEnableNotificationOnlyAlarms": "False", "AMIImage": "ami-123456789" }, "tags": { "CostCenter": "12345", "Owner": "test#test.com" }, "cft_file":
"cft/cft.json"}
The json from the file that does work:
data = { "stack_name": "perf-a", "parameters": { "StackSet": "a", "MonitoringEnableAutoscalingAlarm": "True", "MachineConfigEnvironment": "Perf", "AppEnvironmentType": "perf", "StackInRotation": "True", "MonitoringEnableNotificationOnlyAlarms": "False", "AMIImage": "ami-123456789" }, "tags": { "CostCenter": "45229", "Owner": "test#test.com" }, "cft_file": "
cft/cft.json"}
The code I am using for testing is:
var envFile = "perf2.json";
var fs = require('fs');
console.log('envFile = ' + envFile);
fs.readFile(envFile, 'utf8', function (err, data) {
if (err) {
console.log('error reading variables file');
throw err;
}
try {
var JsonData = JSON.stringify(data);
console.log('JsonData = ' + JsonData);
data = data.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f")
.replace(/\\0/g, "")
.replace(/\\v/g, "")
.replace(/\\e/g, "\\e");
data = data.replace(/[\u0000-\u001F]+/g, "");
console.log('data = ' + data);
var cftVariables = JSON.parse(data);
console.log('cftVariables = ' + cftVariables);
console.log('cftVariables stack name = ' + cftVariables.stack_name);
} catch (e) {
console.log('error parsing variables file');
throw e;
}
});
As you can see, I have also tried JSON.stringify but I lose the properties and cftVariables.stack_name becomes undefined.
This problem has been plaguing me for several days and I am now at a loss as to how to fix it.
For reference, here is the snippet of PowerShell that creates the file. The problem might be there.
$savePath = "envs/" +$filetouse + ".json"
$parameters = #{AppEnvironmentType =$AppEnvironmentType;
StackSet = $StackSet;
StackInRotation = $StackInRotation;
AMIImage = $amiid;
MonitoringEnableAutoscalingAlarm = $MonitoringEnableAutoscalingAlarm;
MonitoringEnableNotificationOnlyAlarms= $MonitoringEnableNotificationOnlyAlarms;
MachineConfigEnvironment = $MachineConfigEnvironment;
}
$tags = #{Owner = "test#test.com";
CostCenter = "45229";
}
$envcft = #{stack_name =$stack_name;
cft_file = "cft/cft.json";
parameters = $parameters;
tags = $tags;
} | ConvertTo-Json
Write-host("Saving the env file with the new amiId... ")
$envcft | Out-File $savePath -Encoding UTF8 -force
Assuming you are reading the data in from a file, once you have the string you can use the remove function to get rid of that "?".
Something like this:
s = s.replace('?','');
EDIT
since the replace did not work, try 1) either not specifying an encoding when you save the file, or 2) specify UTF16

Display \n \r correctly in HTML from JSON

I have a String fetched from a Database and send from a backend using Servlet. The servlet constructs the JSON and send it to the client
I use this function to escape the JSON
public static String toHTML(String string){
StringBuffer sb = new StringBuffer();
for(int i=0;i<string.length();i++){
char ch=string.charAt(i);
switch(ch){
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '/':
sb.append("\\/");
break;
default:
//Reference: http://www.unicode.org/versions/Unicode5.1.0/
if((ch>='\u0000' && ch<='\u001F') || (ch>='\u007F' && ch<='\u009F') || (ch>='\u2000' && ch<='\u20FF')){
String ss=Integer.toHexString(ch);
sb.append("\\u");
for(int k=0;k<4-ss.length();k++){
sb.append('0');
}
sb.append(ss.toUpperCase());
}
else{
sb.append(ch);
}
}
}//for
return sb.toString();
}
But, once displayed, I see the escaped characters. Example "something \r\n".
Any suggestions ?
JavaScript function to replace newline chars
var nl2br = function(str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
console.log(nl2br('asdf', false)); // asdf
console.log(nl2br('as\r\ndf', false)); // as<br>
//
// df
console.log(nl2br('as\n\rdf', true));​ // as<br />
//
// df
\r\n is obivously nothing a browser can interpret. Replace \r\n with <br> and you got your line break in HTML. Replace the other tags accordingly.