Jquery Own Html Text Editor - javascript

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);

Related

Why is innerHTML truncating my string (and how do I fix it)?

I have two simple strings I want to output (both coming from user input). The console.log says that they are properly received by JavaScript into their respective variables, but when I output them via innerHTLM, the first is truncated at the "<" symbol.
JavaScript
var content1 = "Dog- Happy<Hungry", content2 = "Dog- Happy<2Hungry"
console.log(content1,content2)
document.getElementById("output").innerHTML = content1 + "<br>" + content2
Output
Dog- HappyDog- Happy<2Hungry
Expected Output
Dog- Happy<Hungry
Dog- Happy<2Hungry
The input is from users and I want them to be able to use the "<" symbol, as it is a common symbol for this type of input. I am guessing that the "<" is being seen as the beginning of an HTML tag, though I am not sure. How do I solve this, so that they can use the "<" symbol?
Here is a JSFiddle if it is helpful: https://jsfiddle.net/m79dca3p/
Encode html entities in javascript does not help as those responding are split on the best solution, thus it is still an open debate and not a solution.
< is how you start a tag in HTML, and since you use innerHTML the input is treated as HTML.
If you want input to be treated as plain text, use a mechanism that deals in text and not one that deals in HTML.
const content1 = "Dog- Happy<Hungry";
const content2 = "Dog- Happy<2Hungry";
const output = document.getElementById("output");
output.append(document.createTextNode(content1));
output.append(document.createElement('br'));
output.append(document.createTextNode(content2));
<div id=output></div>
Just use innerText instead of innerHTML and add your <br>separateley

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

Convert php's htmlspecialchars() with javascript

I have a variable written from PHP into my javascript (using json_encode), that looks a little like this:
mappoints[x]['about'] = 'Administrator: Foo Barlt;br />Telephone: 555-4202<br />Email: bert#hotmail.com<br />Website: www.domain.com'
That I am using for a google maps map point. Using the json_encode seems to be very picky about what characters I can and cannot enter into it, so i am wondering how I can convert those special html characters into real html characters using javascript?
update
The way i am building my variable is:
var description = "<h3 style='margin: 0; padding: 0;'>" + mappoints[x]['name'] + "</h3><b>Director:</b> " + mappoints[x]['director'] + "<br/>" + mappoints[x]['about'];
The HTML in the varaible is all fine, until I add the about index. No function I have attached or tried yet seems to give me proper HTML.
You can use the dom to decode those entities for you.
mappoints[x]['about'] = 'Administrator: Foo Barlt;br />Telephone: 555-4202<br />Email: bert#hotmail.com<br />Website: www.domain.com'
mappoints[x]['about'] = $('<div/>').append(mappoints[x]['about']).text();
http://jsfiddle.net/5FTCX/
Basically when you add the html to the dom it will show the entities as the characters they represent, using .text() you can receive the data back as you'd see it in the browser as text, not html with the entities. If you want back the html you can use .html() e.g..
Would it be okay with :
return mystring.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
From here : Convert special characters to HTML in Javascript
Just because #Musa's idea was great but needed some re-interpreting on my side, I wish to post a quick function here, that will handle htmlspecialchars great, based on #Musa's design :
function htmlspecialchars_decode(string) {
$('body').append("<span style='display:none;visibility:hidden;' id='tempText'>" + string + "</span>");
var result = $('#tempText').text();
$('#tempText').remove();
return result;
};
try this
decodeURIComponent(str) or `unescape(str)` or `decodeURI(str)`

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