Specifically display the non-printable characters [duplicate] - html

This question already has answers here:
h:outputText does not break \r\n characters into new lines
(3 answers)
Closed 6 years ago.
I am using primefaces and I would like to display to users the non-printable characters ( \n,\t,\r - should be shown as they are, not rendered).
I use the <h:outputText> command. I read the content from a file.
For example, the file has the following content:
test
new line
a new line
In java, windows this renders as: test\n new line\n a new line.
The output should be the same :Hello\n newline\n a new line.
How can I do that? The values are not printed at all:
"Hello new line a new line".
Found solution:
To render properly (e.g '\n' should be displayed) I added a new backslash: \n became \\n.
Thank you,
Luisa

You can use the following method from the Apache Commons project on the desired strings in your backing bean (it escapes all Java-like special characters):
https://commons.apache.org/proper/commons-lang/javadocs/api-3.5/org/apache/commons/lang3/StringEscapeUtils.html#escapeJava-java.lang.String-
Example:
private String escapeString = StringEscapeUtils.escapeJava("Hello \\n this is new line");
public String getEscapeString() {
return escapeString;
}
with
<h:outputText value="#{testViewBean.escapeString}"/>
prints
Hello \\n this is new line

You need to set escape property false as by default it is true.
As explained by MkYong.
https://www.mkyong.com/jsf2/jsf-2-outputtext-example/

Related

How can I do string interpolation? [duplicate]

This question already has answers here:
How can I do string interpolation in JavaScript?
(21 answers)
Closed 3 years ago.
I'm trying to do string interpolation in code using Angular, Typescript, HTML, etc... For some reason the 'dollar sign' appears as a string literal in the output. Can anyone help?
I need the output to as follows:
"Hello World."
Instead, I'm getting this:
"Hello ${name}."
Link:
https://stackblitz.com/edit/angular-template-string-interpolation
Thanks.
To interpolate strings, you need to use template literals
Template literals use ``` (backtick) and not ' (single quote)
Also, name is a class property, so you should reference it by using this
So, your code becomes:
title: string = `Hello ${this.name}.`;
String interpolation only happens inside back ticks.
"Hello ${name}."
produces Hello ${name}. but
`Hello ${name}.`
produces Hello previewFrame in your example. This is because you are referencing the wrong variable. Instead of ${name} use ${this.name} otherwise you're getting the name of the frame that stackblitz renders your output in.
For the record, this is not a typescript or Angular feature. String interpolation is a newer vanilla javascript feature. More info here.
You need to use the this keyword and the back ticks. Like this:
title: string = `Hello ${this.name}.`;

How to format text in WKWebView by wrapping it into HTML using Swift iOS?

I am loading text into a WKWebView. My goal is to:
set font size to a fixed value
align text vertically in the WKWebView
align text horizontally in the WKWebView
I have not been able to find functions on the WKWebView that would do that. So I am trying to wrap the string into some HTML code.
Here is my code:
func loadQuestions() {
questionView.questionLabel.text = questionArray[questionIndex].questionText
let questionText: String = questionArray[questionIndex].questionText!
let answerText: String = questionArray[questionIndex].answerText!
let htmlWrap = "<p>\(questionText)</p><p>\(answerText)</p>"
answerView.webView.loadHTMLString(htmlWrap, baseURL: nil)
}
This works, but the moment I am trying to add some advanced formatting that I get using a converter website (since I don't know html) I get all the quotation marks (") which invalidate my string.
let htmlWrap = "<p style="text-align: center;"><span style="font-size: 36pt;">\(questionText)</span></p><p style="text-align: center;"><span style="font-size: 36pt;">\(answerText)</span></p>"
That above will not compile.
It seems I can use the escape character (\) in the html string before each quotation mark (") and that seems to work if it is a simple line. But does not work for complex html. So how do I do this?
Thank you!
Two ways:
As you already know, using \ is a good way to go around this, because for Swift a string starts with " and ends with ". Adding \ before " with convert it into a part of the string and not the control character specifying the end of the string. So you can copy the output of your converter and paste it in a text editor and find and replace " with \". There is no other way if you want to use " inside the HTML string (if the option of directly getting the html string from your converter using an API to store into a variable is ruled out).
The other way is to use ' instead of " inside the HTML string. So again you will have to copy the output of your converter to a text editor and find and replace " with '.
Method 1: Escaping
As you alluded to in your initial question, you can always escape any embedded quote characters by prefixing the '\' character. If you go this route, I would make two passes in a global find-and-replace: first replace a single backslash () with two backslashes, then replace each quote with \".
Method 2: Multiline String Literal
As of Swift 4.0 (a year and a half old now), you can also use multiline string literals, which are bounded by """ (three double-quotes) to get yourself partway there. You would do it like this:
let htmlWrap = """
<p style="text-align: center;"><span style="font-size: 36pt;">\(questionText)</span></p><p style="text-align: center;"><span style="font-size: 36pt;">\(answerText)</span></p>"
"""
The first line break (before "
Indentation up to the point of the terminating """ will not be preserved. So for instance the string above would not include the extra four-space indent I put in the code sample, because the terminating """ is also indented by four spaces.
Taking text out of some other generator and inserting into your document between the multiline literal string markers should generally be a safe copy-paste except in the very odd situation where you have three quotes actually in your HTML (it has no special meaning in HTML, so would only come if your plain text had that construct in it, such as if you were quoting this answer).
An important thing to note, however, is that escaping in multiline literals still escapes. So, something like this will not end up as it is written:
let testing = "Testing 123"
let htmlWrap = """
<p>\(testing)</p>
"""
... would end up printing "Testing 123" in your web view.
Method 3: Raw Multiline String Literals (Swift 5+)
Swift 5 (in Xcode 10.2 which is in beta now) remedies this by adding Raw Strings, which can also be multiline like so:
let testing = "Testing 123"
let htmlWrap = #"""
<p>\(testing)</p>
"""#
... which will print out "(testing)" in your web view as you might expect.
Method 4: Separate the HTML into its own file
In my opinion, however, if I am dealing with HTML, I put in its own file, and load that text into a string using the String(contentsOfFile: myFile) initializer to load it in. This keeps HTML text in its own file that as a bonus Xcode will be able to intelligently help you with if you ever go in to edit it.

Extract string from HTML tag [VB.Net] [duplicate]

This question already has answers here:
How do I match any character across multiple lines in a regular expression?
(26 answers)
Closed 4 years ago.
How do I match and replace text using regular expressions in multiline mode?
I know the RegexOptions.Multiline option, but what is the best way to specify match all with the new line characters in C#?
Input:
<tag name="abc">this
is
a
text</tag>
Output:
[tag name="abc"]this
is
a
test
[/tag]
Aahh, I found the actual problem. '&' and ';' in Regex are matching text in a single line, while the same need to be escaped in the Regex to work in cases where there are new lines also.
If you mean there has to be a newline character for the expression to match, then \n will do that for you.
Otherwise, I think you might have misunderstood the Multiline/Singleline flags. If you want your expression to match across several lines, you actually want to use RegexOptions.Singleline. What it means is that it treats the entire input string as a single line, thus ignoring newlines. Is this what you're after...?
Example
Regex rx = new Regex("<tag name=\"(.*?)\">(.*?)</tag>", RegexOptions.Singleline);
String output = rx.Replace("Text <tag name=\"abc\">test\nwith\nnewline</tag> more text...", "[tag name=\"$1\"]$2[/tag]");
Here's a regex to match. It requires the RegexOptions.Singleline option, which makes the . match newlines.
<(\w+) name="([^"]*)">(.*?)</\1>
After this regex, the first group contains the tag, the second the tag name, and the third the content between the tags. So replacement string could look like this:
[$1 name="$2"]$3[/$1]
In C#, this looks like:
newString = Regex.Replace(oldString,
#"<(\w+) name=""([^""]*)"">(.*?)</\1>",
"[$1 name=\"$2\"]$3[/$1]",
RegexOptions.Singleline);

Replace characters with HTML entities in Java [duplicate]

This question already has answers here:
XSS prevention in JSP/Servlet web application
(10 answers)
Closed 19 days ago.
I want to replace certain characters with their respective HTML entities in an HTML response inside a filter. Characters include <, >, &. I can't use replaceAll() as it will replace all characters, even those that are part of HTML tags.
What is the best approach for doing so?
From Java you may try Apache Commons Lang (legacy v2) StringEscapeUtils.escapeHtml(). Or with commons-lang3: StringEscapeUtils.escapeHtml4().
Please note this also converts à to à & such.
If you're using a technology such as JSTL, you can simply print out the value using <c:out value="${myObject.property}"/> and it will be automatically escaped.
The attribute escapeXml is true by default.
escapeXml - Determines whether characters <,>,&,'," in the resulting
string should be converted to their corresponding character entity
codes. Default value is true.
http://docs.oracle.com/javaee/5/jstl/1.1/docs/tlddocs/
When developing in Spring ecosystem, one can use HtmlUtils.htmlEscape() method.
For full apidocs, visit https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/HtmlUtils.html
Since most solutions reference a deprecated Apache class, here's one I've adapted from https://stackoverflow.com/a/16947646/3196753.
public class StringUtilities {
public static final String[] HTML_ENTITIES = {"&", "<", ">", "\"", "'", "/"};
public static final String[] HTML_REPLACED = {"&", "<", ">", """, "&apos;", "&sol;"};
public static String escapeHtmlEntities(String text) {
return StringUtils.replaceEach(text, HTML_ENTITIES, HTML_REPLACED);
}
}
Note: This is not a comprehensive solution (it's not context-aware -- may be too aggressive) but I needed a quick, effective solution.

How can i convert/replace every newline to '<br/>'?

set tabstop=4
set shiftwidth=4
set nu
set ai
syntax on
filetype plugin indent on
I tried this, content.gsub("\r\n","<br/>") but when I click the view/show button to see the contents of these line, I get the output/result=>
set tabstop=4<br/> set shiftwidth=4<br/> set nu<br/> set ai<br/> syntax on<br/> filetype plugin indent on
But I tried to get those lines as a seperate lines. But all become as a single line. Why?
How can I make all those lines with a html break (<br/>) ?
I tried this, that didn't work.
#addpost = Post.new params[:data]
#temptest = #addpost.content.html_safe
#addpost.content = #temptest
#logger.debug(#addpost)
#addpost.save
Also tried without saving into database. Tried only in view layer,<%= t.content.html_safe %> That didn't work too.
Got this from page source
vimrc file <br/>
2011-12-06<br/><br/>
set tabstop=4<br/><br/>set shiftwidth=4<br/><br/>set nu<br/><br/>set ai<br/><br/>syntax on<br/><br/>filetype plugin indent on<br/>
Edit
Delete
<br/><br/>
An alternative to convert every new lines to html tags <br> would be to use css to display the content as it was given :
.wrapped-text {
white-space: pre-wrap;
}
This will wrap the content on a new line, without altering its current form.
You need to use html_safe if you want to render embedded HTML:
<%= #the_string.html_safe %>
If it might be nil, raw(#the_string) won't throw an exception. I'm a bit ambivalent about raw; I almost never try to display a string that might be nil.
With Ruby On Rails 4.0.1 comes the simple_format from TextHelper. It will handle more tags than the OP requested, but will filter malicious tags from the content (sanitize).
simple_format(t.content)
Reference : http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html
http://www.ruby-doc.org/core-1.9.3/String.html
as it says there gsub expects regex and replacement
since "\n\r" is a string you can see in the docs:
if given as a String, any regular expression metacharacters it contains will be interpreted literally, e.g. '\d' will match a backlash followed by ‘d’, instead of a digit.
so you are trying to match "\n\r", you probably want a character class containing \n or \r -[\n\r]
a = <<-EOL
set tabstop=4
set shiftwidth=4
set nu
set ai
syntax on
filetype plugin indent on
EOL
print a.gsub(/[\n\r]/,"<br/>\n");
I'm not sure I exactly follow the question - are you seeing the output as e.g. preformatted text, or does the source HTML have those tags? If the source HTML has those tags, they should appear on new lines, even if they aren't on line breaks in the source, right?
Anyway, I'm guessing you're dealing with automatic string escaping. Check out this other Stack Overflow question
Also, this: Katz talking about this feature