I have written a small jQuery script to help me build a styleguide. The script is used to copy and escape a piece of HTML and print it as documentation. My problem, however, is preversing linebreaks in the html. I would love for my escaped HTML to be formatted just like I have typed it. How is that possible?
$('.documentation-element').each(function() {
var HTML = $(this).html();
$(this).next().find('code').text(HTML).html();
});
See full example here:
http://jsfiddle.net/tolborg/nr7fs/
Change the text() method to html():
$(this).next().find('code').html(HTML);
JSFiddle
You're using a <code> tag, but that doesn't preserve line breaks. You need a <pre> tag for that. So wrap your <code> tag inside a <pre> tag and your code should work as is - except you don't need the extra .html() at the end (it doesn't hurt anything, it just doesn't do anything):
$('.documentation-element').each(function() {
var HTML = $(this).html();
$(this).next().find('code').text(HTML);
});
Here's an updated fiddle.
You may also want to tweak the leading whitespace on each line, but what you want there will depend on the output you want.
For example, here's a version that strips leading whitespace and also removes the extra newlines at the beginning and end:
$('.documentation-element').each(function() {
var HTML = $(this).html().trim().replace( /\n\s+/, '\n' );
$(this).next().find('code').text(HTML);
});
Related
I am creating comments from user input and rendering them using Mustache.js after a user clicks 'submit'. I realize I can replace user input line breaks (\n) with <br/> to render as HTML breaks, such as
myString.replace(/\n/g, '<br />');
and I realize I can make Mustache not escape HTML by using triple brackets
{{{myString}}}
However, I would like to escape all user HTML as Mustache would typically do with double braces {{ ... }}, with the exception of allowing line breaks with <br/>
What is the best way to do this? I can replace the line breaks after it has been rendered, but that seems like a very inefficient solution, and I'm thinking there has to be a better way.
Option 1 - Use a pre tag:
It's actually best (or efficient) that you wrap text in a <pre></pre> tag, which will preserve the white space in the text.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre
And enable word-wrap
How do I wrap text in a pre tag?
- http://jsfiddle.net/X5ZY7/
Option 2 - Split your string into lines, and use a mustache each:
comment = userComment.split("\n")
{{#comment}}
{{comment}}<br/>
{{/comment}}
Option 3 - Manually escape your string using your favorite method before injecting the tags:
var div = document.createElement("div")
div.textContent = comment
comment = div.innerHTML.replace(/\n/g, "<br/>")
{{{comment}}}
If you're looking to add line breaks to a textarea you need to replace \n with
I'm trying to grab an element's HTML using jQuery and then post it to the server. I successfully grabbed it, but I am not able to remove the white space between the tags and the line breaks that are rendered by default. The HTML code grabbed is shown below:
<table><tbody><tr><th></th><th>1</th><th>2</th><th>3</th><th>4</th><th>5</th><th>6</th><th>7</th></tr>
<tr><th>2nd row</th><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr></tbody></table>
I would like to trim the spaces between the tags only. I've used this regular expression: str.replace(/\s+/g, ' ');. But that doesn't seem to work, any suggestions?
Currently, you are replacing all consecutive sequences of whitespace with a single space.
This is what you want:
str.replace(/>\s+</g, '><');
I need to add escape character(backslash - ) character at the end of each line to wrap the string.
For some reason wordpress randomly inserts "blank" paragraph tags on my page. I'm finding it difficult to match the tag.. It seems like it's not completly empty but some weird character I cannot see, it's not there in the source code but generated by javascript so it's very hard to figure out what it is!!
My JS file is loaded last in <head>.
I'm new to regex in javascript..
it looks like this in firebug (not sure if there is a small space/tab/something or not)
<p></p>
My javascript to remove it:
jQuery(window).load(function() {
var page = jQuery('body').html();
page.replace('/\<p\>\S*\<\/p\>/', '');
jQuery('body').html(page);
});
Use jQuery empty selector instead which select all elements that have no children (including text nodes). Try this.
jQuery(window).load(function() {
jQuery('body').find('p:empty').remove();
});
You know the exact string, so what's the matter with just matching just that?
page.replace('/\<p\>\<\/p\>/','');
I'm having trouble properly displaying values that contain escaped characters (i.e. apostrophes are stored as \' and not ' and brackets are > and < rather than > and <).
Items stored in my database have the characters (' < >) escaped to (\' < >), respectively. When I try to dynamically add them to the page with JavaScript, they print out in the escaped form in Firefox, rather than returning to their normal values like in IE (< is being printed to the HTML rather just <).
<html>
<head>
<script type="text/javascript">
$(document).ready(function() {
var str = ">";
$(document.body).html(str);
});
</script>
</head>
<body>
</body>
</html>
I know that if I simply do a replace, I can print correctly, but by doing so, I'm allowing the injection of HTML code, which is why I escaped the string in the first place.
ADDED:
Firstly, I apologize about the mistakes in my initial post. After closer examination, in the instances where I am using $().html(), the strings are printing correctly. The times where they aren't printing correctly are when I am using code like below.
var str = ">";
$('#inputField').val(str);
In this instance, the text ">" is shown, rather than ">". Is there something I can do to fix this?
You need to decode them like this:
$('#myText').val($("<div/>").html(str).text());
Demo: http://jsfiddle.net/QUbmK/
You can move the decode part to function too and call that instead:
function jDecode(str) {
return $("<div/>").html(str).text();
}
$('#myText').val(jDecode(str));
First off, you can't run the code you have in your example. document.body is not ready for manipulation in the HEAD tag. You have to run that after the document has loaded. If I put your code in a safe place to run, it works fine as you can see here.
So ... there must be more to your situation than the simple example you show here. You can see your simple example works fine here when the code is put in the right place:
http://jsfiddle.net/jfriend00/RDSNz/
That doesn't happen, at least not with jQuery. If you do, literally: $(document.body).html('<div>'), you will get <div> printed to the screen, not a div tag. If you're doing something not listed in your question:
either use .text() instead of .html() or replace all & with &:
$(document.body).text(str);
$(document.body).html(str.replace(/&/g, '&'))
I have a pre element with some html code in it.
the code has special characters in it, like <, so it doesn't break the page.
Then I have a javascript function that gets the contents of this pre element, highlights it (with codemirror), and replaces the element contents with the highlighted text.
I'm using $("pre").append(...); to do this.
The problem is that after the highlighting, on the screen I see < instead of <.
How can I convert these characters back to html?
You should be using the .text() method to grab the code from the pre. This way you are't giving the encoded symbols to the code highlighter.
I don't know what happens (and why it happens) to your html, but you can use jQuerys .text() and .html() to decode/encode html entitiys like:
HTML
<div id="test"><<</div>
jQuery:
var t = $('#test');
t.html(t.text()); // will print "<<"
example: http://www.jsfiddle.net/fphw3
update
Since you mentioned that you use .html() to read the value of your element, a call to .text() instead should solve your issue.