Understanding the specifics of the jquery text() with HTML Entities - javascript

I have trouble understanding the specific of the jquery text() function in combination with HTML Entities. It seems to be that the text() function converts special HTML Entities back to normal characters. In particular, I am unsure how this code snippet behaves:
$(document).ready(function() {
var value = $("#test").text();
console.log(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<h1> test </h1>
</div>
since the output seems to be a string where HTML Entities are unescaped. Does this mean that the text() function unescapes HTML Entites?
EDIT/FOLLOW UP:
Since text() seems to only return the real text content, I have trouble understanding this code snippet, which returns an unescaped . If text() returns the escaped string, why does the html function return a formatted one?
$(document).ready(function() {
var value = $("#test").text();
console.log(value);
$("#test").html(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<h1> test </h1>
</div>

text() isn't doing anything special. The browser itself translates entities into their rendered characters when it parses the original HTML. So when you write <h1> in the HTML, the browser converts this to the literal string <h1>. .text() simply returns this text.
When you then use .html(), this causes the string to be parsed as HTML, so <h1> is rendered as an HTML tag, and you get the formatted result.

If you look at the source you'll see that it is pulling out the textContent from elements.
https://j11y.io/jquery/#v=git&fn=jQuery.fn.text
Some documentation of what textContent is:
https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
$(document).ready(function() {
var value = $("#test").text();
console.log(value);
//https://j11y.io/jquery/#v=git&fn=jQuery.fn.text
console.log($("#test").get(0).textContent);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<h1> test </h1>
</div>

Related

Get a part of string from a page source code (information is present in HTML)

How can I look for a keyword in a HTML source code and get a value from the code using Pure JS. There are multiple code tags and I am looking to extract the value 12345 and it can be in any <code> block which doesn't have a unique ID or class. The keyword (word to find in any code tag) to find would be "THIS_IS_WHAT_IAM_LOOKING_FOR".
Example:
HTML source code:
<html>
<body>
(some HTML goes here)
<code style="display: none">
wlkdw,dmnewf4oi4j4f4knkf4kjfkfjk;fefiekf;flegelgjelkghjreg;THIS_IS_WHAT_IAM_LOOKING_FOR12345,95849;fefjefefmdl;fljegflegc;evev;evk;evke;v;evirvrkvjrkvuve;vkev;ejv;
</code>
<code style="display: none">
fffffffffffekjfekfjekfjrgkrgkjkthjtkhjtkhjtkhjkthp;gkrg2;4l3lgfrgrgkrg9;fefjefefmdl;fljegfleg w;c;evev;evk;evke;v;evirvrkvjrkvuve;vkev;ejv;
</code>
</body>
</html>
You can use split() to get the part of the string you are interested in, for instance, in your case, i assume you have the mentioned text before the value and a comma after:
const d0 = htmlCode.split('THIS_IS_WHAT_IAM_LOOKING_FOR')[1] // After this text
.split(',')[0]; // Before this
console.log(d0);
Example working in stackBlitz
https://stackblitz.com/edit/js-hqqvrl?file=index.js
There are probably more elegant ways to do this, but this one should work.

jQuery 'HTML function doesn't work with special characters

I am trying to pass the string "{<A+_2OF3_MSF}" to jQuery's HTML function. It doesn't work because of special character <. I tried encoding/escaping an HTML tag using this escapeHtml function, but I am facing another issue after that.
var escapeHtml = function(theString) {
return theString.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
};
It appends HTML-encoded string as text, not as HTML. I saw the below Stack Overflow post, but then it suggests to decode it after encoding. If I do that I am back to square one.
Appending HTML-encoded string as HTML, not as text
I have created a fiddle:
https://jsfiddle.net/1aktfzm8/
You need to use .text() instead of .html()
$(document).ready(function(){
$("button").click(function(){
$("p").html("<span id=\"span\"> {A+_\"2OF3_MSF\"} </span>");
$('#span').text();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Change content of all p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
This code is working normally: https://jsfiddle.net/kilotonna/eg4be1gr/1/
$(document).ready(function(){
$("button").click(function(){
$("p").html("{<A+_2OF3_MSF}".replace(/</g, '<'));
});
});

knockout.js best way to bind html string in textarea with line breaks

I've got the html string that I'd like bind with knockout.js and display it in textarea, and of course allow submitting it after some editing. What is the proper way to achieve that?
When I use HTML binding, I can bind one <br/> two string and it displays the same in textarea, but after submitting, I get the encoded string one<br/>two, which isn't too bad as I can handle it later, but there's still the line breaks issue.
Basically I'd like to preserve:
original line breaks
original html text
Now, when I pass:
<html>
<body>
using both value and html binding, in knockout I get script exception, as new lines are not handled. Special characters are encoded as well:
Content: ko.observable("<html>
<body>
Any ideas?
You might want to use btoa to encode the actual value so that no munging goes on in submission. Then you would use atob to decode on the server. Here's a little demo that lets you see how various treatments of html come out.
ko.applyBindings({stuff: ko.observable('<h1>Foo</h1>hi\nthere')});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<textarea data-bind="value:stuff"></textarea>
<pre data-bind="text:stuff"></pre>
<hr />
<pre data-bind="html:stuff"></pre>
<hr />
<pre data-bind="text: btoa(stuff())"></pre>

Generating a string literal from text in JavaScript

<html>
<script>
function printStringLiteral(theInput) {
document.body.innerHTML += JSON.stringify(theInput.value)
}
</script>
<body>
<p>Text to modify:<p>
<input type="text" id = "textInput">
<a onclick="printStringLiteral(document.getElementById('textInput'));" href="javascript:void(0);">Get string literal</a>
</body>
</html>
I'm trying to create a simple web page that accepts text as input and returns a string literal, but this web page doesn't display the string literal correctly after it has been generated. I entered <p>"Hi!"</p> as input, but "\"Hi!\"
was displayed as output, instead of the correctly formatted string literal. What will I need to do here in order to get the string to display properly?
Instead of setting the innerHTML, set the text
function printStringLiteral(theInput) {
document.body.textContent += JSON.stringify(theInput.value)
}
If you need to support IE8- you need to set innerText too

Passing rendered html to a javascript function

I have some html code rendered on the server side. This is passed to a jsp which renders a javascript-call with this html:
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", "${content}");
</script>
content is like
"
This is a <p class="xyz">test</p>
"
My problem is that - according to the quotes in 'content' - the javascript-call is wrong as it is rendered to
<script type="text/javascript">
window.parent.${param.popup_return}("ybc", "This is a <p class="xyz">test</p>");
</script>
Does anyone know how I can solve this (besides manually replacing all quotes)?
Use a JSON encoder to create the encoded strings.
But you'll also have to ensure that the output doesn't contain the sequence </ in string literals, which is invalid in a <script> block (</script is the version that will also break browsers).
Many JSON encoders either by default or optionally will encode to <\/ or \u003C/ to avoid this problem.
I use this:
<div id="result" style="display:none">
${content}
</div>
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", dojo.byId("result").innerHTML);
</script>
This seems to work perfectly
You aren't using JSTL here (you originally tagged the question with only JSTL). You are using EL in template text. It get printed plain as-is. You'd like to use JSTL core <c:out> to escape predefined XML entities (which also works for HTML in this particular case, quotes is among the escaped XML entities).
window.parent.${param.popup_return}("<c:out value="${helpId}" />", "<c:out value="${content}" />");
An alternative (if you hate that the JSP syntax highlighter or validator bugs/jerks about nested tags/quotes) is the JSTL function fn:escapeXml():
window.parent.${param.popup_return}("${fn:escapeXml(helpId)}", "${fn:escapeXml(content)}");
Have you tried using single quotes instead of double quotes? i.e. changing "${content}" to '${content}'

Categories