Using a variable in a Blogger JSON-LD template - javascript

I'm refering to the question JSON-LD: Using data:post.body in Blogger template.
Surprisingly, <data:post.body> can be used in the meantime. But now I have a new problem: How to eliminate tags, linefeeds and special characters and replace characters like ' and "?
I found something in the kind of the following instead of directly write JSON-LD code, but it does not work:
<script type='text/javascript'>
var thisDdoesNotWork = removeHtmlTags_And_ChangeSomeCharacters("<data:post.body/>");
var el = document.createElement('script');
el.type = 'application/ld+json';
el.text = JSON.stringify({
"v1":"thisWorks",
"v2":"<data:post.thisWorksToo/>",
"v3":thisDdoesNotWork});
document.querySelector('head').appendChild(el);
Someone an idea?

Firstly render the content somewhere in the HTML via
<div class='post-body'>
<data:post.body/>
</div>
Then, change your code as follows -
el.text = JSON.stringify({
"v1":"thisWorks",
"v2":"<data:post.thisWorksToo/>",
"v3":document.querySelector('.post-body').textContent});
You can also use innerText property (Refer to this question to know the difference between innerText and textContent)

Related

Why am I getting an error when trying to add the src attribute to an img tag using JavaScript within Colfusion?

I am using ColdFusion to connect to and execute methods from a Web Service. I store the contents of the returned xml string in to a ColdFusion array then I convert the ColdFusion array into a JavaScript array, so that I may populate the content of my HTML document.
My problem arises when trying to add a photo to a unordered list called "agent_photo_list". Specifically when I call the .setAttribute method. It seems to involve the 'src' parameter. The JavaScript code works as I expect when it is not inside the cfscript tag and WriteOutput method. I have researched the problem, I haven't been able to find a reference that is sufficiently similar. I am still having trouble understanding what my problem is. I have included my code below:
cfscript>
WriteOutput('
<script language = "JavaScript">
var #ToScript(array, "jsArray")#
var agent = jsArray[0];
document.getElementById("output").innerHTML = agent.firstname + " " + agent.lastname;
var imgurl = "_images/agentphoto.jpg";
var node = document.createElement("LI");
var imgnode = (document.createElement("IMG"));
imgnode.setAttribute('src', "imgurl");
node.appendChild(imgnode);
document.getElementById("agent_photo_list").appendChild(node);
</script>
')
</cfscript>
I am using a jpg file located in my _images folder for testing purposes, I will later change it to agent.photourl.
The error I get is provided below:
Invalid CFML construct found on line 117 at column 35.ColdFusion was
looking at the following text:<p>src</p><p>The CFML
compiler was processing:<ul><li>An expression beginning
with WriteOutput, on line 111, column 17.This message is usually
caused by a problem in the expressions structure.<li>A script
statement beginning with WriteOutput on line 111, column
17.<li>A cfscript tag beginning on line 102, column 10.</ul> The specific sequence of files included or processed is: C:\inetpub\wwwroot\webservice.cfm, line: 117
I am curious to why my JavaScript is functional inside the cfscript tag until calling the setAttribute method and why it is functional outside the cfscript tag.
I will appreciate your insight. Thank you.
You need to wrap the src in "". Also, add the ";" at the end of WriteOutput closure. The below code should work for you.
<cfscript>
WriteOutput('
<script language = "JavaScript">
var #ToScript(array, "jsArray")#
var agent = jsArray[0];
document.getElementById("output").innerHTML = agent.firstname + " " + agent.lastname;
var imgurl = "_images/agentphoto.jpg";
var node = document.createElement("LI");
var imgnode = (document.createElement("IMG"));
imgnode.setAttribute("src", "imgurl");
node.appendChild(imgnode);
document.getElementById("agent_photo_list").appendChild(node);
</script>
');
</cfscript>

Parse HTML string containing script tag and document.write

I have below string. It has nested document.write string statements. I want to add text contents of innermost script to document.
"document.write('<script>document.write(\"<script>document.write(\"Hello World\");<\/script>\");<\/script>')"
How can I parse this string so that Hello World gets added in document. For e.g. html output can be as below.(can be in body or div, anything is ok.)
<body>Hello World</body>
P.S. there can be any number of nested document.write statements. Need to parse this string which can handle n level of nesting.
Well I figured it out now.
var str = "document.write('<script>document.write(\"<script>document.write(\"Hello World\");<\/script>\");<\/script>')";
var aStr, scriptEle = document.createElement('script');
aStr = str.replace(/["']/g, '"');
aStr = aStr.replace(/"<script>document.write/g, "");
aStr = aStr.replace(/;<\/script\>"/g, "");
scriptEle.innerHTML = aStr;
// console.log(aStr);
document.body.appendChild(scriptEle);
This also handles n level of nesting.
You will basically have to tell the script to execute the script inside the <script> tags.
You can achieve this by doing this
var code = "<script>document.write(\"Hello World\");</scr"+"ipt>";
$('body').append($(code)[0]);
Which will happily display hello world in the body tags. You can use this approach to get your script executed by appending it on any tag. Here is the jsfiddle and an SO answer that can give you an idea as to how to be able to execute a js which gets appended dynamically
Hope that helps :)

Having trouble including JavaScript Variable in HTML

I have a file with this code:
var famname = guterriez;
And another HTML file family.html where I have included the location of the file in the head. I need to display the variable in a p element, and possibly in other locations on my site.
I would appreciate some help / tips on how to do this as I've done some research and nothing seems to be working.
If guterriez is not another variable but a string, then you have to put it into quotation marks. Like mentioned above.
Something like this might work for you, if you want to display the code in various locations on your page:
I.e. if you have a <div> or a <table> where you want to dispaly it:
<div id="MyDiv"></div>
<table id="MyTable"><tr><td id="MyCell"></td></tr>
The following JS Code will display the code in the mentioned above elements by calling them with their ID:
<script>
document.getElementById("MyDiv").innerHTML = famname;
document.getElementById("MyCell").innerHTML = famname;
</script>
Below is an example of how to integrate your JS file into your HTML, and reference variables defined there:
config.js
var txtVar = "This is some text";
page.html
<script src="config.js" />
<p id="textBlock"></p>
<script>
document.getElementById("textBlock").innerText = txtVar;
</script>
See code snippet below for a runnable example.
var txtVar = "This is some text";
window.onload = function() {
document.getElementById("textBlock").innerText = txtVar;
};
<p id="textBlock"></p>
I'm assuming guterriez is a string that you would like to assign to the variable famname. In that case, it needs to be enclosed in quotation marks to denote the fact that it is a string rather than a variable named guterriez (which presumably doesn't exist).
Try this:
var famname = "guterriez";
Then, you want to use innerText to assign this value to the p element in your HTML file. Try using document.getElementsByTagName("p")[index] to access the node and then assign innerText:
document.getElementsByTagName("p")[0].innerText = famname;
var famname = "guterriez";
document.getElementsByTagName("p")[0].innerText = famname;
<p></p>

How to find and replace text in between two tags in HTML or XML document using jQuery?

I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;

Is there a way to convert HTML into normal text without actually write it to a selector with Jquery?

I understand so far that in Jquery, with html() function, we can convert HTML into text, for example,
$("#myDiv").html(result);
converts "result" (which is the html code) into normal text and display it in myDiv.
Now, my question is, is there a way I can simply convert the html and put it into a variable?
for example:
var temp;
temp = html(result);
something like this, of course this does not work, but how can I put the converted into a variable without write it to the screen? Since I'm checking the converted in a loop, thought it's quite and waste of resource if keep writing it to the screen for every single loop.
Edit:
Sorry for the confusion, for example, if result is " <p>abc</p> " then $(#mydiv).html(result) makes mydiv display "abc", which "converts" html into normal text by removing the <p> tags. So how can I put "abc" into a variable without doing something like var temp=$(#mydiv).text()?
Here is no-jQuery solution:
function htmlToText(html) {
var temp = document.createElement('div');
temp.innerHTML = html;
return temp.textContent; // Or return temp.innerText if you need to return only visible text. It's slower.
}
Works great in IE ≥9.
No, the html method doesn't turn HTML code into text, it turns HTML code into DOM elements. The browser will parse the HTML code and create elements from it.
You don't have to put the HTML code into the page to have it parsed into elements, you can do that in an independent element:
var d = $('<div>').html(result);
Now you have a jQuery object that contains a div element that has the elements from the parsed HTML code as children. Or:
var d = $(result);
Now you have a jQuery object that contains the elements from the parsed HTML code.
You could simply strip all HTML tags:
var text = html.replace(/(<([^>]+)>)/g, "");
Why not use .text()
$("#myDiv").html($(result).text());
you can try:
var tmp = $("<div>").attr("style","display:none");
var html_text = tmp.html(result).text();
tmp.remove();
But the way with modifying string with regular expression is simpler, because it doesn't use DOM traversal.
You may replace html to text string with regexp like in answer of user Crozin.
P.S.
Also you may like the way when <br> is replacing with newline-symbols:
var text = html.replace(/<\s*br[^>]?>/,'\n')
.replace(/(<([^>]+)>)/g, "");
var temp = $(your_selector).html();
the variable temp is a string containing the HTML
$("#myDiv").html(result); is not formatting text into html code. You can use .html() to do a couple of things.
if you say $("#myDiv").html(); where you are not passing in parameters to the `html()' function then you are "GETTING" the html that is currently in that div element.
so you could say,
var whatsInThisDiv = $("#myDiv").html();
console.log(whatsInThisDiv); //will print whatever is nested inside of <div id="myDiv"></div>
if you pass in a parameter with your .html() call you will be setting the html to what is stored inside the variable or string you pass. For instance
var htmlToReplaceCurrent = '<div id="childOfmyDiv">Hi! Im a child.</div>';
$("#myDiv").html(htmlToReplaceCurrent);
That will leave your dom looking like this...
<div id="myDiv">
<div id="childOfmyDiv">Hi! Im a child.</div>
</div>
Easiest, safe solution - use Dom Parser
For more advanced usage - I suggest you try Dompurify
It's cross-browser (and supports Node js). only 19kb gziped
Here is a fiddle I've created that converts HTML to text
const dirty = "Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>";
const config = { ALLOWED_TAGS: [''], KEEP_CONTENT: true, USE_PROFILES: { html: true } };
// Clean HTML string and write into the div
const clean = DOMPurify.sanitize(dirty, config);
document.getElementById('sanitized').innerText = clean;
Input: Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>
Output: Hello world Many other tags are stripped
Using the dom has several disadvantages. The one not mentioned in the other answers: Media will be loaded, causing network traffic.
I recommend using a regular expression to remove the tags after replacing certain tags like br, p, ol, ul, and headers into \n newlines.

Categories