How can I format text in an HTML <textarea>? - javascript

I have a <textarea> on my page, and when I click a button, the value of the text in the textarea is assigned to .innerHTML of a paragraph on my page.
Now let's say I type something like this in the textarea:
Hey
how's
it
going
?
The paragraph would look like this
Hey how's it going ?
Basically, it wouldn't have <br> tags at the end of each row. Is there a way I can force the JavaScript function to insert <br> tags at the end of each row of my textarea, or is there an easier way to do this?
JavaScript code:
document.getElementById("sendMsgBtn").onclick = function(){
var element = document.createElement("p");
element.style.borderBottom = "1px solid black";
var content = document.createTextNode(document.getElementById("currentMsg").value);
content = content.replace(/\n/g, "<br>");
element.appendChild(content);
document.body.appendChild(element);
document.getElementById("currentMsg").value = "";
}

You don't want line breaks. Trust me.
Just set this:
white-space: pre-wrap;
This CSS will make whitespace significant, preserving it as it was typed.

When you copy the element from the textarea to the paragraph tag, replace all line breaks with <br> tags:
var input = document.getElementById("myTextarea").innerHTML; // get textarea contents
input = input.replace( /\n/g, "<br>"); // replace line breaks with <br> tags
document.getElementById("myParagraph").innerHTML = input; // place html-ified input into your <p>

If you are using jQuery, try this:
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
Then nl2br(yourVariableWithContent); can be used to change newline characters (the ones that the return button makes) into <br/>.

Related

Replace Form Input Selected Text

I have an old asp page that had a small image that could be clicked to change some selected text in a form text input box to italics using javascript. This was working fine for many years, but a user just informed me that it no longer seems to be working. In looking around for a solution, it seems the createRange() function is no longer supported by many current browsers, causing the browser to throw an error, and getSelection() should now be used instead.
The old script is listed below.
<script type="text/javascript">
var j; // this is the currently selected form element i.e., line number
function getelement_num(k) {
j = k;
return;
}
function format_sel(v) {
var str = document.selection.createRange().text;
document.form1.strMessage.focus();
var sel = document.selection.createRange();
sel.text = "[" + v + "]" + str + "[/" + v + "]";
return;
}
</script>
I have modified the format_sel function as follows:
function format_sel(v) {
var str = window.getSelection().toString;
document.FrontPage_Form2.elements[j].focus();
var sel = window.getSelection().toString;
sel.text = "<" + v + ">" + str + "</" + v + ">";
return;
}
So, the getSelection() seems to be working fine. If I alert(sel), it returns the selected text. However, the sel.text portion is not replacing the selected text in the input field of the form.
My question is, how should I modify the code above so that the selected text in the form input field will be replaced with the modified text as found in sel.text?
Pertinent HTML code (with only 1 of 9 form fields shown for brevity):
<a title="Select text in fields below and then click this button to add Italics" href="#" onclick="format_sel('i');" ><img alt="Select text in fields below and then click this button to add Italics" border="0" src="images/italic.gif" width="21" height="19" align="middle" class="style33" /></a>
<input name="Title" id="Title" type="text" placeholder="Add Title" style="border: 1px solid #B5DB38; width: 250px" onfocus="lastFocus=this; getelement_num('0');" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);" /></td>
I should note that I also have code that will insert special characters into the form as well, which is what the storeCaret code is for. That seems to work fine.
Many thanks for the assistance.
There seem to be two types of problem with this code.
The first one is that if you want to get the string value of the selection, you should use toString() instead of toString. Using the latter will give you a reference to the function toString instead of the returned value. I don't know what your alert function is calling, but it doesn't seem correct.
The second problem is that your sel variable is currently a function, and even if you did it correctly (using toString()) you would get a string which has no .text attribute. What you should be calling there is actually
var sel = window.getSelection();
So that you get a reference to the Html Element, which does have the .text attribute.
Ok, in searching around a little bit, I found some code that seems to work. I modified it slightly for my own purposes (see below), but the original code by Er. Anurag Jain can be found here: https://stackoverflow.com/a/11170137/2121627.
Many thanks as well to #user2121627 for their suggestions on amending and testing the code.
<script type="text/javascript">
var j; // this is the currently selected form element i.e, line number
function getelement_num(k) {
j = k;
return;
}
function format_sel(v) {
var elem = document.FrontPage_Form2.elements[j];
var start = elem.selectionStart;
var end = elem.selectionEnd;
var len = elem.value.length;
var sel_txt = elem.value.substring(start, end);
if (sel_txt != "") {
document.FrontPage_Form2.elements[j].focus();
var replace = "<" + v + ">" + sel_txt + "</" + v + ">";
elem.value = elem.value.substring(0, start) + replace + elem.value.substring(end, len);
}
}
</script>
Here is a jsfiddle for those interested: https://jsfiddle.net/jwfetz/kzcywvnh/42/

try to show html tags as text with innerHTML

I have a string that contains HTML tags.
I want to render as an HTML element only the span tags aka <span></span>.
every other tag that is not a span tag should be treated as regular text.
The result I'm trying to achieve is to color any text that I want even if it contains HTML tags.
I fail.
is there any other technique that I can try or a workaround?
var problem = ["<h1>","</h1>"];
var red_text = "<span style='color:red'>i am red </span>";
var green_text = "<span style='color:green'>" +
problem[0] +
"i am green" +
problem[1] +
"</span>";
//the real result should have <h1> </h1>
var expected_text = red_text + "<span style='color:green'>|h1|i am green|/h1|</span>";
document.getElementById("demo").innerHTML = red_text + green_text;
document.getElementById("expected").innerHTML = expected_text;
HTML and JavaScript code at :
https://jsfiddle.net/ytLftxww/1/
You need to use HTML entities to escape the < and > in those tags.
For example: "<span style='color:green'><h1>i am green</h1></span>"
See the fiddle: https://jsfiddle.net/ytLftxww/1/
var problem = ["<h1>","<h1>"];
does unescaping the < > work for you?
updated fiddle
You can use &lt for < and & &gt for >.

getting the innerHTML after finding the innerText

I have a RegEx to find the part of the text I want :
var re = RegExp("(?:^\\W*|(" + motBefore.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ")\\W+)" + motErreur.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "(?:\\W+(" + motAfter.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ")|\\W*$)", "g");
var resultMatch = document.getElementById('edth_corps').innerText.match(re);
Like this I can retrieve back the part of the text I need to modify with the punctuation. The trouble I get from here is to retrieve the innerHtml of this so I can get if in this part there is tag around the "motErreur".
I need to have to innerHTML because the purpose of my function is to wrap a span around the motErreur but this :
var reInner = resultMatch[0].replace(new RegExp("\\b" + motErreur + "\\b", "gi"), '<span id="'+nbId+'" class="erreurOrthographe" oncontextmenu="rightClickMustWork(event, this);return false">' + motErreur + '</span>');
document.getElementById('edth_corps').innerHTML = document.getElementById('edth_corps').innerHTML.replace(resultMatch, reInner);
does not work since between the innerText and the innerHTML it is possible to have tag already wrap around the part of text I get.
Example :
Input => this, tset, that; result : work fine because innerHTML and innerText are the same (no tag to mess up the search)
Input2 => this, <em>tset</em>, that; result : does not work since the innerText and the innerHTML are not the same (resultMatch is not the same as variable as what it is in the last replace).
I actually have no idea how to link these two thing correctly in the simplest way possible.
Configuration : javascript, compiled in quirks mode (only utility on IE, i don't care about other browser).
The trouble I get is that if there is already a span around motErreur
Assuming the innerHTML you get can only have a tag around your mot erreur you could check if there's a span this way :
if (theInnerHtml.firstChild) {
// It has at least one
var yourSpan = document.createElement('span');
// you set the innerHTML of yourSpan with the innerHTML of the child
// Ex <p> blablabla <em>motErreur</em> blabla </p>
// yourSpan will be "<span>motErreur</span>"
yourSpan.innerHTML = theInnerHtml.firstChild.innerHTML;
// you empty the innerHTML of your the child
// It will be <p> blablabla <em></em> blabla </p>
theInnerHTML.firstChil.innerHTML = "";
// Then you append your span to the firstChild
// It will be <p> blablabla <em><span>motErreur</span></em> blabla </p>
theInnerHTML.firstChild.appendChild(yourSpan):
}
This therefore implies that your innerHTML will only have 1 possible child, and that this child will be wrapping your motErreur

how to replace a string in javascript after the specific index

Hi I am having the string which contains html content and I want use javascript to replace the tag <p class="MsoNormal"> with '' empty space and i want to replace corresponding closing tag </p> with <br> tag in that string.
If I use
first line:
str=str.replace(/<p class=\"MsoNormal\">/g,'');
second line: str=str.replace(/<\/p>/g,'<br>');
All the closing </p> tag get remove .But i want to replace the closing </p> tag which has the opening tag of "<p class="MsoNormal">".
The first line of script is okay of me .What should i use to replace that corresponding closing tag in the second line.
Check this: Output is what I got from your question is to replace with Empty String
var replaceTag = function(str, replaceTagString, endTagString) {
var str = '';
while(str.indexOf(replaceTagString) != -1) {
//search for </p> after my matched String
var indexOfClosingTag = str.indexOf(endTagString, str.indexOf(replaceTagString))
//Replace </p> using Substring
str = str.substr(0,indexOfClosingTag) + "<br>" + str.substr(indexOfClosingTag + endTagString.length,k.length)
//Replace your main String
str = str.replace(replaceTagString,'')
}
return str
}
var k = "<p class='MsoNormal'>something</p><p>other p tag</p><h1>I am h1</h1><p>Hello p</p><p class='MsoNormal'>Replace My Tag too</p>"
replaceTag(k, "<p class='MsoNormal'>", "</p>")
Output:
"something<p>other p tag</p><h1>I am h1</h1><p>Hello p</p>Replace My Tag too"
Concept:
string.indexOf(searchvalue,start)
Start searching for End of the Tag (P) after my current matched string position
Define a function yourself like this-->
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
And use it like this:
str = str.replaceAt(3, "</p>");

Add a span tag inside p after certain amount of characters

Suppose you have this for your HTML:
<div class="contentBox">
<p>I have some content that is good to read</p>
</div>
However you would like to add a span tag after a certain amount of characters, lets say 26 characters, which would be right after the word "that". The result would look like this:
<div class="contentBox">
<p>I have some content that<span> is good to read</span></p>
</div>
It has to be after a certain amount of characters, because the paragraph will change from time to time.
Set the amount of characters after you want to set the span. Get text of the p element. Substring from start until the amount of chars, add the span, continue with the rest and add the closing span
Try:
var after=26;
var html = $(".contentBox p").html();
html = html.substring(0, after) + "<span>" + html.substring(after)+"</span>";
$(".contentBox p").html(html);
DEMO
String.prototype.insertTextAtIndices = function (text) {
return this.replace(/./g, function (char, index) {
return text[index] ? text[index] + char : char;
});
};
//usage
var range = {
25: "<span style='color:red'>",
40: "</span>"
};
document.getElementsByTagName("p")[0].innerHTML = document.getElementsByTagName("p")[0].innerHTML.insertTextAtIndices(range);
http://jsfiddle.net/4zx37Lhm/1/
You can make use of JavaScript's substr method.
function addSpan($elems) {
$elems.each(function() {
var $elem = $(this),
text = $elem.text();
if (text.length <= 25)
return;
var start = text.substr(0, 25), // "I have some content that "
end = text.substr(25, text.length); // "is good to read"
$elem.html(start + '<span>' + end + '</span>');
});
}
addSpan($('.contentBox').find('p'));
span {
color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="contentBox">
<p>I have some content that is good to read</p>
</div>
<div class="contentBox">
<p>I have some content that is good to read and this is a much longer string!</p>
</div>
Try this : get first part and second part of the string using substring() and modify text with span element to put it into html of p tag.
Below function will iterate all p under contentBox div, but if you are targeting only one div then you can use it without .each()
$(function(){
$('.contentBox p').each(function(){
var text = $(this).text();
var first = text.substring(0,26);
var second = text.substring(26,text.length);
$(this).html(first + '<span>' + second + '</span>');
});
});
DEMO

Categories