I have a template for Underscore.js that does not get rendered. My problem is explained in this JSFiddle.
// this string will get loaded by an ajax call and put in a variable when the application starts
var allTemplates = '<section id="header">header template</section> <section id="content"><% var test = 10 %><%= test %></section>"';
// put it in the DOM to parse it with jQuery
$('#test').html(allTemplates);
var getSpecificTemplate = function(templateID) {
return $('#test').find('#' + templateID).html();
};
var templateData = getSpecificTemplate('content');
// expected log output: 10
// actual log output: <% var test = 10 %><%= test %>
console.log( _.template(templateData, {}) );
// why?
This setup equals pretty much my code. What could be the problem? Why is the template even encoded?
If I understand you correctly, you're not evaluating your template, you're appending a literal string.
Change this: $('#test').html(allTemplates);
to this:
var templateString = _.template(allTemplates, {});
$('#test').html(templateString);
Then you will see the expected outcome in your console.log(), also in your console.log() you can simply put the following:
var templateData = getSpecificTemplate('content');
console.log(templateData);
Fiddle: http://jsfiddle.net/KyleMuir/my3NW/6/
Hope this helps!
Your approach is perfectly fine. What you have missed on is the call to .html().
Your templateData variable is messed up because .html() in this line -
return $('#test').find('#' + templateID).html();
escapes the content. Change .html() to .text() and this should work.
http://jsfiddle.net/q5Q7e/
Edit: CORRECT APPROACH -
The above doesn't work because .text() only gets the 'text', skipping the elements.
What you need to do is, add your template in a script tag and not section tag. This way,
when you make a .html() call on the element, you will get unescaped html (jQuery doesn't bother escaping when .html() is called on a script tag).
Here, make this change
OLD
var allTemplates = '<section id="header">header template</section> <section id="content"><% var test = 10 %><%= test %></section>"';
NEW
var allTemplates = '<section id="header">header template</section> <script type="text/template" id="content"><a href="#“><% var test = 10 %><%= test %></a></script>"';
I couldn't get this to work with jsfiddle.net, so here is a plnkr.co
Related
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 :)
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;
I am dumping some CSS into a div and I am looking to format it so it is more legible. Basically what I want to do is insert a break tag after every semicolon. I have searched around for a while but can't seem to find something that quite fits what I am trying to do.
I have something like this...
HTML
<div class='test'>
color:red;background-color:black;
</div>
jQuery
var test = $('.test').text();
var result = test.match(/;/g);
alert(result);
And I have tried..
var test = $('.test').text();
var result = test.match(/;/g);
result.each(function(){
$('<br/>').insertAfter(';');
});
alert(result);
Also I have started a fiddle here.. Which basically just returns the matched character...
http://jsfiddle.net/krishollenbeck/zW3mj/9/
That is the only part I have been able to get to work so far.
I feel like I am sort of heading down the right path with this but I know it isn't right because it errors out. I am thinking there is a way to insert a break tag after each matched element, but I am not really sure how to get there. Any help is much appreciated. Thanks...
try it like this
var test = $('.test').text();
var result = test.replace(/\;/g,';<br/>');
$('.test').html(result);
http://jsfiddle.net/Sg5BB/
You can use a normal javascript .replace() method this way:
$(document).ready(function(){
$(".test").html($(".test").html().replace(/;/g, ";<br />"));
});
Fiddle: http://jsfiddle.net/SPBTp/4/
Use This CODE
var test = $('.test').text();
var result = test.split(';').join(';<br />')
http://jsfiddle.net/FmBpF/
You can't use jQuery selectors on text, it only works on elements.
Get the text, just replace each ; with ;<br/>, and put it back.
$('.test').html($('.test').text().replace(/;/g, ';<br/>'));
Try something like this :
var test = $('.test').text();
var result = test.replace(/;/g,";");
$('.test').html(result);
That should work if you stick it into your jfiddle.
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.
I have some lines of HTML code that are like this:
<li>Testing jQuery [First Bracket]</li>
<li>Loving jQuery [Second one]</li>
I'm trying to replace what's inside the bracket with nothing onLoad, like this:
var item = $(".lstItem").text();
var match = item.match(/\[(.*?)\]/);
item = item.replace(match[0], "");
But nothing changes. What's wrong and how to correct this?
After using jimbojw's suggestion I'm getting a Uncaught ReferenceError: text is not defined at this particular line:
oldtext = $item.text,
item is a variable containing a string, not a pointer to the literal text. If you want to change the text, you have to set it again, vis a vis $(".listItem").text(item)
edit - predicting next problem
The next problem you're going to have is that all the text gets set to the same thing. So what you really want to do is probably something like this:
$(".lstItem")
.each(function(index, item) {
var
$item = $(item),
oldtext = $item.text(),
match = oldtext.match(/\[(.*?)\]/),
newtext = oldtext.replace(match[0], '');
$item.text(newtext);
});
this will do the job for you:
you are splitting your code in too much lines, also your need to run replace for each individual element separately.
$(".lstItem").each(function() {
$(this).html(
$(this).html().replace(/\[(.*)\]/, "")
);
});
see your example in jsFiddle: http://jsfiddle.net/eKn3Q/7/
Along with jimbojw's answer $(".lstItem").text() will retrieve all the text inside of your <a/> elements. One way to handle this would be to pass a function(i,t){} into the .text() method.
$(".lstItem").text(function(i, text){
var match = text.match(/\[(.*?)\]/);
return text.replace(match[0], "");
});
Simple example on jsfiddle
also your regex could be simpler.
var item = $(".lstItem").text();
var match = /\[(.*?)\]/;
$(".listItem").text(item.replace(match,""));