I have a variable in JavaScript that contains the contents of an html textarea. When I print the variable all that were entered by the user are forgotten. Is there any way to find the spaces in the string so I can separate each line?
here is a function , you can use for your script:
function nl2br (str) {
var breakTag = ''; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
HTML collapses adjacent whitespace - so if you are displaying within HTML, that's what you are seeing.
You can replace spaces with non break spaces: - this will ensure they are displayed in HTML and not collapsed.
Another option is to place them in a <pre> element
You mean all newlines? HTML ignores newlines and collapses whitespace by default. Print them inside a <pre> tag, or check out the CSS white-space property: http://www.w3schools.com/cssref/pr_text_white-space.asp
You can also replace newlines with <br> tags using:
while (str.indexOf("\n") > -1) str = str.replace("\n","<br>");
Related
I want to render a text as common HTML and parse occurrences of [code] tags that should be output unrendered - with the tags left untouched.
So input like this gets processed accordingly:
<p>render as HTML here</p>
[code]<p>keep tags visible here</p>[/code]
<p>more unescaped text</p>
I've regexed all code-tags but I have no idea how to properly set the text of the element afterwards. If I use jQuery's text() method nothing gets escaped, if I set it with the html() method everything gets rendered and I gained nothing. Can anybody give me a hint here?
Try replacing [code] with <xmp> and [/code] with </xmp> using regex or alike, and then use the jQuery html() function.
Note that <xmp> is technically deprecated in HTML5, but it still seems to work in most browsers. For more information see How to display raw html code in PRE or something like it but without escaping it.
You could replace the [code] and [/code] tags by <pre> and </pre> tags respectively, and then replace the < within the <pre> tags by & lt;
A programmatic solution based on Javascript is as follows
function myfunction(){
//the string 's' probably would be passed as a parameter
var s = "<p>render as HTML here</p>\
[code]<p>keep tags visible here</p>[/code]\
<p>more unescaped text</p>";
//keep everything before [code] as it is
var pre = s.substring(0, s.indexOf('[code]'));
//replace < within code-tags by <
pre += s.substring(s.indexOf('[code]'), s.indexOf('[/code]'))
.replace(new RegExp('<', 'g'),'<');
//concatenate the remaining text
pre += s.substring(s.indexOf('[/code]'), s.length);
pre = pre.replace('[code]', '<pre>');
pre = pre.replace('[/code]', '</pre>');
//pre can be set as some element's innerHTML
return pre;
}
I would NOT recommend the accepted answer by Andreas at all, because the <xmp> tag has been deprecated and browser support is totally unreliable.
It's much better to replace the [code] and [/code] tags by <pre> and </pre> tags respectively, as raghav710 suggested.
He's also right about replacing the < character with <, but that's actually not the only character you should replace. In fact, you should replace character that's a special character in HTML with corresponding HTML entities.
Here's how you replace a character with its corresponding HTML entity :
var chr = ['&#', chr.charCodeAt(), ';'].join('');
You can replace the [code]...[/code] with a placeholder element. And then $.parseHTML() the string with the placeholders. Then you can insert the code into the placeholder using .text(). The entire thing can then be inserted to the document (run below or in JSFiddle).
var str = "<div><b>parsed</b>[code]<b>not parsed</b>[/code]</div>";
var placeholder = "<div id='code-placeholder-1' style='background-color: gray'></div>";
var codepat = /\[code\](.*)\[\/code\]/;
var code = codepat.exec(str)[1];
var s = str.replace(codepat, placeholder);
s = $.parseHTML(s);
$(s).find("#code-placeholder-1").text(code);
$("#blah").html(s);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Text
<div id="blah">place holder</div>
Around
The code above will need some modifications if you have multiple [code] blocks, you will need to generate a unique placeholder id for each code block.
If you may be inserting untrusted structure code, would highly recommend using large random number for the placeholder id to prevent a malicious user from hijacking the placeholder id.
Hi I am using the following code :
breakContent = breakContent.replace(/<div>/g, ' <div>');
Here breakContent is a string that contains html code. I need to provide space before div tag.The above code works fine for div without any attribute like id, style,etc...
So what I need is the working code including attributes in div tag...
I tried the below code..but it does not give space before div and instead it replace the div with space
breakContent = breakContent.replace(/<div\s*[\/]?>/gi, " ");
Just change it to:
breakContent = breakContent.replace(/<div/g, ' <div');
Removing the trailing > will allow for <div> tags with attributes.
EDIT: Of course, this could pick up text that isn't actually a <div> tag, if you have text matching <div that isn't a tag.
When adding in text with small whitespace appended to it for alignment purposes the whitespace is trimmed off (the whitespace is added in c# so by the time it gets to front end Javascript it cannot be edited - it would be nice to just use some CSS to do this but it is not an option).
Here is what I tried so far:
var zlp = document.getElementById("testDiv")
zlp.innerHTML = "hello hello"
var zzz = document.createTextNode("hello hello")
zlp.appendChild(zzz)
<div id="testDiv"></div>
Both of which produce hello hello.
White space characters are usually collapsed in HTML (by default).
You can replace it with the entity:
var text = text.replace(/\s/g, ' ');
\s will match any white space character, such as space, tab and new line. If you only want to replace space, use / /g instead.
Other options which avoid string manipulation:
Put the text in a pre element.
Set the CSS 2 white-space property to pre as #Esailija pointed out. You can always add CSS properties dynamically to elements, they don't have to be specified in a style sheet.
use
zlp.innerHTML = "hello hello";
Like everyone else just said.
use a html tag 'pre'
Example:
<pre>
A line
A line with indent
</pre>
result:
A line
A line with indent
White space is collapsed in HTML. It's not a JS issue, the same would happen if you typed that manually in the HTML document. You need to replace the spaces with
zlp.innerHTML = "hello hello".replace( / /g, " " );
I would like to remove the initial space in a textarea. When there is no text given to a textarea and you get the textarea.value, you get a single space " " instead of the empty string like a normal input textbox.
Also when there is text (i.e. test) it returns " test". Is it possible to prevent this extra space?
I would prefer to work with the prototype of Textarea because I am using a general procedure to get the values of both input textboxes and textarea's.
For the moment I wrote something like this:
Textarea.prototype.value = function() {
var val = this.value;
if (val[0] == "0") val.splice(0,1);
return val;
};
But it doesn't solve the problem, I still get the extra space.
Your HTML should be like this:
<textarea></textarea>
---------^ no space, tab or new line there
Simply make sure that there is no space between opening and closing tags eg follwing are wrong:
<textarea> </textarea>
Or
<textarea>
</textarea>
Correct:
<textarea></textarea>
" \b" would result in "". So you could concatinate the string with \b to eliminate the last character of a string
I have a HTML input text, and its values are populated from a related div. My problem is that the div contains characters like & which will display correcly as '&' sign in div but when copied to text box the text '&' will be dispalyed
How can i convert & to & and '<' to '<', ' ' to ' ' ???
You thus want to unescape HTML entities. With plain JS you can use this snippet:
function unescapeHTML(html) {
var div = document.createElement("DIV");
div.innerHTML = html;
return ("innerText" in div) ? div.innerText : div.textContent; // IE | FF
}
And with jQuery the following one:
function unescapeHTML(html) {
return $("<div />").html(html).text();
}
But you can also just fix this problem during the step that you "copy" the div's content into the input element's value. Instead of grabbing HTML, just grab text. Instead of element.innerHTML, that'll be element.innerText for IE or element.textContent for real browsers.
No, you can't and shouldn't do this (reliably) with regex.
I am not sure how you are accessing data but a possible solution could be use of innerText property instead on innerHtml