Formatting text file using jquery - javascript

Here is my question,
I have a text file and I am reading the file using jquery.
the code is here
$(function() {
$.get('files/james.txt', function(data) {
$('.disease-details').html(data);
}, 'text');
});
but I am getting only plain text and all formatting is disappearing.
I want to convert all the enter in to p tag. is it possible?

You can do this :
$(function() {
$.get('files/james.txt', function(data) {
data = data.split("\n");
var html;
for (var i=0;i<data.length;i++) {
html+='<p>'+data[i]+'</p>';
}
$('.disease-details').html(html);
}, 'text');
});
The above splits up the text by new line (the text-"formatting") and wraps each chunk into a <p> .. </p> .. Exactly as requested.

By definition, a plain-text file has no formatting to begin with (hence the "plain" part).
If you mean newline characters, those are not rendered in HTML by default. To overcome this, you can simply wrap your text with a <pre> tag which among other things is rendered including newline characters.
For example:
$(function() {
$.get('files/james.txt', function(data) {
$('.disease-details').html($('<pre>').text(data)); // Text wrapped in <pre>
}, 'text');
});

You will either have to get the file pre-formatted using HTML tags / or just get the data from the text file and do a client side formatting ( using templates or otherwise ). Can give you better pointers if you give sample of what the data in the file would look like

Related

Adding space between words while rendering the contents from a .txt file using JS/Jquery

I am trying to display the contents of my .txt file in a div. However, I want to insert additional space between certain words. I know editing the file system directly using JS is not a good idea. However, Is there any way of adding the spaces between the word at the time when it is rendered in the webpage.
My HTML :
<div id= "show-content"></div>
JQuery code :
function readFile() {
$.get('data.txt', function(txt) {
console.log(txt)
$("#show-content").load("data.txt");
}, 'text');
}
My Text file (data.txt) looks something like :
Blaine Nemec
Alphonse Smither
Lon Garrick
Rob Hennings
Erin Tatham
Stefan Stacks
Allen Dang
Rolf Aultman
Jeff Christenson
Mohamed Croswell
Ambrose Mina
Rhett Jahnke
The display list is coming correctly. However, I want to add some additional space after each name. If its not possible to edit the .txt file, is it possible to achieve this in CSS or JS/JQuery. I have searched several stack overflow questions related to editing files, but none was in JavaScript and couldn't help me out.
EDIT: I am trying to add 3 or 4 additional space depending on the font family, after each name in the .txt file.
You can split the .txt words with the .split() method and than stylize them.
Something like this:
function readFile() {
$.get('data.txt', function(txt) {
console.log(txt)
myWords = txt.split("\n");
for (word of myWords) {
$("#show-content").append("<span class="beautyWord">" + word + "</span>")
}
}, 'text');
}
Then stylize the beautyWord class in your css with something like margin-left: 5px
Okay first of all, you are making the ajax request two time. One in .get and one in .load. Use .get only, you can alter the test of txt variable like:
function readFile() {
$.get('data.txt', function(txt) {
cont newText = txt.split("\n")
.map(el => el + " ")
.join("\n");
$("#show-content").html(newText);
});
}
Split string using \n
Add a certain amount of spaces
Join back using \n
Set the variable as html.
I don't know what you are trying to achieve by additional spaces, but here's basic JS code for it.
//change number of spaces according to your need
//you can also use &nbsp for it
var EXTRA_SPACE = ' ';
function readFile() {
$.get('data.txt', function(txt) {
console.log(txt)
var names = txt.split('\n').map(item => getElement(item + EXTRA_SPACE));
$("#show-content").html(name);
}, 'text');
}
//change how each individual name element should look like
function getElement(name) {
return '<div>' + name + '</div>';
}
P.S. generally we use CSS padding and margin around the element to achieve that

Jquery Own Html Text Editor

I'm trying make my own html text editor. Like you see picture. I wrote bold, italic, there is no problem.
But when i wrote code (like html code), like you see only write "Test", But I wrote in textarea <p>Test</p>
And I'm using SyntaxHighlighter plugin for display my codes.
And you see my code below
function Textarea(input, preview) {
var text = input.val().replace(/\[b\]/g, "<b>").replace(/\[\/b\]/g, "</b>")
.replace(/\[i\]/g, "<i>").replace(/\[\/i\]/g, "</i>")
.replace(/\[u\]/g, "<u>").replace(/\[\/u\]/g, "</u>")
.replace(/\[s\]/g, "<s>").replace(/\[\/s\]/g, "</s>")
.replace(/\[img\]/g, "<br/><p></p><img src='").replace(/\[\/img\]/g, "' /><br/><p></p>")
.replace(/\[link/g, "<a").replace(/URL="/g, "href='").replace(/"\]/g, "'>").replace(/\[\/link\]/g, "</a>")
.replace(/\[code/g, "<pre").replace(/type="/g, "class='brush:").replace(/"\]/g, "'>").replace(/\[\/code\]/g, "</pre>");
preview.html(text);
}
I know it cause for preview.html(text), I need also write like preview.text(text) code.
But I dont know, how can i do this?
Thanks.
a quick way is to create a element inject the html code as text, then get it back out as html, then the tags, and other characters, should then be in entity form, eg < as < etc
$('<div></div>').text(input.val()).html().replace...
But there are some issues with it, eg whitespaces maybe removed
Because of that this answer shows creating a function that you can use to encode characters, which just encodes the <,>,",',& characters. You could add other characters to the replace to extend the function.
So what you need to do is html encode the raw text given by the user, then replace the bracket entities with html, and finally set the html of the output div. Here's a simple example of that:
http://jsfiddle.net/2K97x/
String.prototype.htmlEncode = function () {
return $('<div/>').text(this).html();
};
function replaceEntities(value) {
return value.replace(/\[b\]/g, "<b>").replace(/\[\/b\]/g, "</b>")
.replace(/\[i\]/g, "<i>").replace(/\[\/i\]/g, "</i>")
.replace(/\[u\]/g, "<u>").replace(/\[\/u\]/g, "</u>")
.replace(/\[s\]/g, "<s>").replace(/\[\/s\]/g, "</s>")
.replace(/\[img\]/g, "<br/><p></p><img src='").replace(/\[\/img\]/g, "' /><br/><p></p>")
.replace(/\[link/g, "<a").replace(/URL="/g, "href='").replace(/"\]/g, "'>").replace(/\[\/link\]/g, "</a>")
.replace(/\[code/g, "<pre").replace(/type="/g, "class='brush:").replace(/"\]/g, "'>").replace(/\[\/code\]/g, "</pre>");
}
var rawValue = $('input').val();
var htmlEncoded = rawValue.htmlEncode();
var newHtml = replaceEntities(htmlEncoded);
$('div').html(newHtml);

JSON pretty print with highlighting

I would like to pretty print JSON on a web page and highlight some text / lines in it.
Ideally I am searching for a IFRAME - service to which I can link and URL where the JSON get's donwloaded and displayed as HTML, but I would like to specify an search string, which should be highlighted or the whole line containing the search string should be highlighted. The JSON is public so there is no privacy issue.
If there is no such service, is there a Javscript library which supports highlighting?
Focusing in more on your question about iframes - it's an issue in itself. It's not possible to do what you want in an iframe if the domain names aren't the same. However there are some workarounds for the same-origin policy that could help you in this situation.
Ideally the service you're pulling from supports jsonp so you don't have to deal with iframes and can do what you like with the json response without worrying about the same-origin policy.
As mentioned in a previous answer of mine you can use Prettify to apply syntax highlighting, though you can't highlight a specific line (from what I've found so far). For this example I'll be using the GitHub API.
For the HTML, you would have:
<pre id="jsonCode" class="prettyprint lang-json"></pre>
And the JavaScript to fetch and pretty print the JSON response (switch out jquery if you'd like):
$.getJSON('https://api.github.com/users/trevorsenior?callback=?',
function(data) {
var jsonString = JSON.stringify(data, null, 4);
$('#jsonCode').text(jsonString);
prettyPrint(); //apply syntax highlighting to to JSON
});
You can look at a working demonstration here: http://plnkr.co/edit/RiDtloVflmfuOrAokNXE?p=preview
If you do decide to use Prettify take a look at their getting started guide.
Update
To fully answer your question, it is easy enough to add in highlighting to some text by wrapping the text in <span> tags with a specified class. I've thrown together another example of this that builds off of the previous one: http://plnkr.co/edit/FM6Ua4pOvMW7nFFggdBy?p=preview
In a nutshell:
.highlighted {
background-color: #ff0;
}
$('#search').keyup(function() {
var search = $('#search').val();
if(jsonString.match(search)) {
var regex = new RegExp(search, 'g');
var highlighted = '<span class="highlighted">' + search + '</span>';
var newJsonString = jsonString.replace(regex, highlighted);
$('#jsonCode').html(prettyPrintOne(newJsonString));
} else {
$('#jsonCode').html(prettyPrintOne(jsonString));
}
});
If you want to remove the dynamic functionality & highlight on load simply move the logic out from the event listener:
var highlight = function(jsonString, searchFor) {
var regex = new RegExp(searchFor, 'g');
var highlighted = '<span class="highlighted">' + searchFor + '</span>';
var newJsonString = jsonString.replace(regex, highlighted);
return prettyPrintOne(newJsonString);
};
And call it just before you populate the area with the code
$('#jsonCode').html(highlight(jsonString, 'X-RateLimit'));
Demonstration: http://plnkr.co/edit/be3SNq1TzeiPKXohXOk9?p=preview

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.

preserving line feeds in text extracted from HTML

I have an html table that is being rendered on a web page that I using in a jquery lookup to plug values into textarea.
The table that is rendered on has <td>s with data like this
<td class="ms-vb"><p>Hello. </p><p> line2</p>
and
<div>1</div><div>2</div><div>3</div>
which appears like this on the page.
Hello
line 2
and
1
2
3
I'm using some jquery to pull that data of the hmtl table and insert it into a textarea textbox.. but when I do I'm just see a long string of text without the html tags and certainly no line feeds.
What's a good jquery or javascript way to insert that data into my textearea field that at least linefeeds are preserved in the textarea?
So basically I need a function that would turn this string
Any way in jquery or javascript for form that html data so that at least line feeds are preserved in my multiline textarea?
=== full code here.. basically doing a lookup of some table on my page and using it to plug in values in a two textxboxs:
<script type="text/javascript">
$('select[title$=Issue Type] option:eq(0)').text("Please Select").val("");
$('select[title$=Issue Type]').change(function(){
var issue = $('select[title$=Issue Type] :selected').text();
var bodyprefixes = [];
$('#issuetbl td:contains('+issue+')').nextAll().each(function(i, k) {
bodyprefixes.push($(k).text());
});
$('input[title$=Subject]').val(bodyprefixes[1]);
$('input[title$=Message]').val(bodyprefixes[0]);
});
</script>
Try using regex. If you want to to support other tags, you will have to include them in the regex. The one here supports also:
$('#txtarea').text(
$('td.ms-vb').text()
.replace(/<\/?(br|div|p)\/?>/g, "\n\n")
.replace(/<[^>]+>/g, "")
);
note: you may need to trim quadruple '\n' from your output.
Something like:
var textAreaInput = '';
var getTextFromElement = function() {
textAreaInput += $(this).text() + '\n';
};
$('p').each(getTextFromElement);
$('div').each(getTextFromElement);

Categories