Currently I have a bunch of text stored in an array. When I output that in the console I see the new lines being kept. If I output that into a textarea it works great and I have new lines, but I can't format the text with different colors (I need selections color coded based on keywords)
What I want to do is have the look of the text area with the new lines but output it to something like a <div><p>array output here</p></div> but keep the new lines. Whatever I try it breaks them and I see all the text together.
Here is the code that I'm using:
//Works great but not format friendly as in colors
$('#textarea').val(myArray)
//format friendly colors but does not keep new lines
$('div[title^="divContainer"]').find('p').text(myArray);
any suggestions to have the best of both worlds?
Thanks
Loop through array and replace() \n with <br> and use html() method
var myArray = ["\nFirst test", "\n\nSec\nond test", "\nThird Test"],
text = myArray.join(''),
html = myArray.reduce((a, c) => a + c.replace(/\n/g, '<br>'),'');
$('#textarea').val(text);
$('div[title^="divContainer"] p').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div title="divContainer">
<p>Test</p>
</div>
<textarea disabled rows="10" cols="15" id="textarea"></textarea>
var myArray = ["hello","world"] ;
for (var i; i<myArray.length; i++)
{
var result = $('div[title^="divContainer"]').find('p').text(myArray[i] + '\n');
result.html(result.html().replace(/\n/g,'<br/>'));
}
In plain JavaScript (I used <br> for the line breaks):
var myArray = ["Hello, my name is Test1.",
"Hello I'm Test2.",
"Hello, I'm Test3."];
for (var i = 0; i < myArray.length; i++) {
document.getElementById("myDiv").innerHTML =
document.getElementById("myDiv").innerHTML + myArray[i] + "<br>";
}
<div id="myDiv"></div>
Related
Hey :) I know a similiar question was asked before, but i just cant get it through. I want to create a method called something like makeMeSpaces, so my h2 text will have a space between each character.. and i might want to use it elsewhere aswell. I have this until now, from the logic point of view:
var text = "hello";
var betweenChars = ' '; // a space
document.querySelector("h1").innerHTML = (text.split('').join(betweenChars));
it also works pretty fine, but i think i want to do
<h2>Hello.makeMeSpaces()</h2>
or something like this
Thank you guys!
If you really want this in a 'reusable function,' you'd have to write your own:
function addSpaces(text) {
return text.split('').join(' ');
}
Then, elsewhere in code, you could call it like so:
var elem = document.querySelector('h2');
elem.innerHTML = addSpaces(elem.innerHTML);
Maybe this is what you want , not exactly what you showed but some what similar
Element.prototype.Spacefy = function() {
// innerText for IE < 9
// for others it's just textContent
var elem = (this.innerText) ? this.innerText : this.textContent,
// replacing HTML spaces (' ') with simple spaces (' ')
text = elem.replace(/ /g, " ");
// here , space = " " because HTML ASCII spaces are " "
space = " ",
// The output variable
output = "";
for (var i = 0; i < text.length; i++) {
// first take a character form element text
output += text[i];
// then add a space
output += space;
};
// return output
this.innerHTML = output;
};
function myFunction() {
var H1 = document.getElementById("H1");
// calling function
H1.Spacefy();
};
<h1 id="H1">
<!-- The tags inside the h1 will not be taken as text -->
<div>
Hello
</div>
</h1>
<br />
<button onclick="myFunction ()">Space-fy</button>
You can also click the button more than once :)
Note :- this script has a flow, it will not work for a nested DOM structure refer to chat to know more
Here is a link to chat if you need to discuss anything
Here is a good codepen provided by bgran which works better
I need to add a " (Quote) to the beginning and a "& _ (Quote ampersand and Underscore) to the end of each line, within a Textarea, when a button is pressed.
Example
Before, the content of the textarea looks like this:
This is line 1
This is line 2
etc...
After, the content of the textarea would look like this:
"This is line 1"& _
"This is line 2"& _
"etc..."& _
Just split your textarea content by \n and do the desired editing and you can then join them back using join() function in javascript.
Set this value back to the textarea.
Sample Code
function foo() {
var str = document.getElementById("test").value;
var lines = str.split("\n");
for(var i=0; i<lines.length; i++) {
lines[i] = "\"" + lines[i] + "\"& _";
}
document.getElementById("test").value = lines.join("\n");
}
<textarea id="test"></textarea>
<button onclick="foo()">Click Me!</button>
<textarea id="txtString"></textarea>
<script>
var txtString = $("#txtString");
txtString = str.split("\n");
var afterString = '';
for (var i =0; i = txtString.length; i++) {
afterString += '"'+txtString[i]+'"& _';
}
$("#txtString").val(afterString);
</script>
Hope u want this type something.. Enjoy :)
As I know, writing a new line is "\n", so I tried many times but it wasn't working. This is my source code and screen shot of result
var ary3 = new Array('seven','eight', 'nine');
for (var i =0; i<ary3.length ; i++){
document.getElementById('demo3').innerHTML += i+"'\nth element\n[enter image description here][1] : " + ary3[i]+"\n";
}
<h1>Show me the array object's entry</h1>
<div id = 'demo3'></div>
<br>
Whitespace is generically collapsed to at most a single space in HTML. Example
<div>a
b c</div>
Will appear as just a b c
You have a few options
Use pre
<pre>a
b</pre>
Will appear as
a
b
Use white-space: pre; CSS on your div
<div style="white-space: pre;">a
b</div>
Will break line breaks
Insert <br/> for `\n' as in
var someString = "a\nb\nc";
someElement.innerHTML = someString.replace(/\n/g, "<br/>");
As for your specific example of looping you also have the option to insert separate elements
function insertDivWithText(parent, text) {
var div = document.createElement("div");
div.appendChild(document.createTextNode(text));
parent.appendChild(div);
}
var demo3 = document.querySelector("#demo3");
var ary3 = ['seven','eight', 'nine'];
for (var i = 0; i < ary3.length ; ++i) {
var div = document.createElement("div");
insertDivWithText(demo3, i + "th element");
insertDivWithText(demo3, "[enter image description here][1] : " + ary3[i]);
}
<h1>Show me the array object's entry</h1>
<div id = 'demo3'></div>
<br>
Also note that using .innerHTML with user data is likely going to expose you to scripting vulnerabilities. Consider using document.createTextNode or element.textContent or element.innerText
The problem is that the newline from JS will be rendered as plain space. HTML is responsible for new line showing, but HTML will not pay attention to simple new line in text. You can check your HTML using developer's tools. You will see that JS made new lines:
derveloper tools
To make new line work, you should add <br /> tag
var ary3 = new Array('seven','eight', 'nine');
for (var i =0; i<ary3.length ; i++){
document.getElementById('demo3').innerHTML += i+"'<br/>\nth element<br/>\n[enter image description here][1] : " + ary3[i]+"<br/>\n";
}
<h1>Show me the array object's entry</h1>
<div id = 'demo3'></div>
<br>
You are writing HTML, DOM, so you have to use <br> tag, not newline.
If you are trying to create a HTML new line, use <br>.
Html code for new line is <br>.
As in:
document.getElementById('demo3').innerHTML += i+"'nth element<br>[enter image description
Your output is html. In html, use the <br /> tag to break the line.
I have an array in javascript file called newElements.
The format likes this:
newElements: Array[3]
0: "<p class='Day'>asdasd</p>"
1: "<p class='Day'>123123</p>"
2: "<p class='Day'>Test</p>"
length: 3
And I have a div.panel-body.
What I did is
for( var i = 0; i < newElements.length; i++) {
new_content += newElements[i];
}
$(".panel-body").text(new_content);
It gives me output looks like this:
However, I want the div format like this:
<p class="Day">Some Text</p>
<p class="Day">Another Text</p>
<p class="Session">TEXT</p>
Each html tag on a separate line.
Yes, I know the <br> tag, but the question is, if I add <br> , the <br> tag will be treated as plain text, the output will become like this: <p class="Day">asdasd</p><br><p class="Day">asds</p>
So, could someone give me a nice way to show the output to screen the way I want it. You already have the array I give you.
And if I use html() function, the <p> will be treated as real html tag, that's not what I want, I want they be shown.
If you don't want to display the code, instead of .text(), use .html().
Fiddle: http://jsfiddle.net/q4AeR/
My mistake. Since you DO want to show the actual code, add each to its own new element, within the loop. This is the best I can think of:
Fiddle: http://jsfiddle.net/Hb9mC/
Try
for( var i = 0; i < newElements.length; i++) {
$(".panel-body").append(document.createTextNode(newElements[i])).append('<br/>');
}
http://jsfiddle.net/9z3zE/1/
I assume you want to display your code including line breaks. Convert your HTML to entities and add line breaks:
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
var newElements = ['<p class="Day">asdasd</p>,<p class="Day">123123</p>,<p class="Day">Test</p>'],
output = '';
for(var i = 0; i < newElements.length; i++) {
output += htmlEntities(newElements[i]) + '<br />';
}
$('.panel-body').html(output);
http://jsbin.com/mefuhufo/1/edit
<div class="hello">
</div>
<script>
var mycars = new Array();
mycars[0] = "<p class='Day'>Hello Xinrui Ma</p>";
mycars[1] = "<p class='Day'>this is the array</p>";
mycars[2] = "<p class='Day'>hopes it fits your need</p>";
var divHello = $('div.hello')
$.each(mycars, function( index, value ) {
divHello.append(value);
});
</script>
I got an HTML string as :var code; I want to extract all hyper link title values in this big string and place them in textarea. I tried the following but it never works. could any one tell me what i am doing wrong?
sample hyperlinks to look for(i want to extract mango,cherry,...) :
mango
cherry
my code string has blocks of data like below:
<div class="details">
<div class="title">
mango
<span class="type">3</span>
</div>
</div>
full code:
$.getJSON('http://anyorigin.com/get?url=http://asite.com/getit.php/&callback=?', function(data){
//$('#output').html(data.contents);
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents ;
var start = siteContents.indexOf('<ul class="list">');
var end = siteContents.indexOf('<ul class="pag">', start);
var code = siteContents.substring(start, end);
document.myform2.outputtext2.value = code ;
var pattern = /<a href="([^"]+?)">([^<]+?)<\/a>/gi;
code = code.match(pattern);
for (i = 0; i < code.length; i++) {
document.write($2<br />'));
}
});
</script>
It looks like you're trying to parse HTML with regex. This post has some more info on that topic.
Since this question is tagged as jQuery, you could try something like the following...
Make a jQuery object out of the returned HTML:
$markup = $(data.contents);
Find the anchors:
$anchors = $markup.find('a');
Get the text (or whatever attribute you want from it):
arrText = [];
$anchors.each(function() {
arrText.push($(this).text());
});
Put result into textarea:
$textarea.val(arrText.join(','));
To achive this jquery is the simplest solution, you can try below code
$('a').each(function(){
var copiedTitle = $(this).html();
var previous = $('#test').html();
var newText = previous +"\n"+ copiedTitle;
$('#test').html(newText);
});
JS Fiddle