In java I send 30 frames (30 Strings) using:
for(Frame frame : frames) {
response.getWriter().write(frame.toString());
}
And I fetch it in my Ajax Post request as:
success: function (result) {
console.log(result);
document.getElementById('logs').innerHTML = '<br>' + result ;
}
HTML:
<div id="logs" class="text-center" style="margin-top: 25px;">
</div>
But I get all the lines mixed into 18 lines. Seems like the <br> doesn't work.
How can I exactly print each String in each line of the HTML?
There are 2 alternatives. First, you can add the line breaks when you build the response in your Java method...
response.getWriter().write("<br />" + frame.toString());
or (depending on whether you need to prepend or append the line breaks)
response.getWriter().write(frame.toString() + "<br />");
Secondly, you could split the response (assuming their are line breaks) and rejoin with Html line breaks, using Javascript...
document.getElementById('logs').innerHTML = '<br>' + result.split("\n").join("<br/>");
The second option depends on the format of the response data, so the first option is probably your best bet.
As "Nick A" mentioned in his comment, you should append new result to the contents of your <div> element instead of replacing it. So your Ajax function should be something like this (= replaced with +=):
success: function (result) {
console.log(result);
document.getElementById('logs').innerHTML += '<br/>' + result ;
}
Edit:
The main issue is that you're appending all data to the result on your server without putting any delimiter so that you could separate them on the client. You can also try adding the <br/> on your server side code as below:
for(Frame frame : frames) {
response.getWriter().write(frame.toString() + "<br/>");
}
and then use your original ajax function on the client side.
Assuming that result is just one big string that contains the string representation of any given frame, you just missed adding a new line here:
for(Frame frame : frames) {
response.getWriter().write(frame.toString() + '<br/>');
}
I prepared two short examples for you:
What you currently do:
var p = document.getElementById('myP');
var frames = new Array('FrameA', 'FrameB', 'FrameC');
var result = '';
// append each frames without adding a new line
for (var i = 0; i < frames.length; i++) {
result += frames[i];
}
p.innerHTML = result;
<p id="myP"></p>
What you want to do:
var p = document.getElementById('myP');
var frames = new Array('FrameA', 'FrameB', 'FrameC');
var result = '';
// appending the frames with adding newlines
for (var i = 0; i < frames.length; i++) {
result += frames[i] + '<br/>';
}
p.innerHTML = result;
<p id="myP"></p>
Related
Not certain if this can be done in regexp under javascript, but thought it would be interesting to see if it is possible.
So thought I would clean up a piece of html to remove most tags, literally just dropping them, so <H1><img><a href ....>. And that would be relatively simple (well, stole the basis from another post, thanks karim79 Remove HTML Tags in Javascript with Regex).
function(inString, maxlength, callback){
console.log("Sting is " + inString)
console.log("Its " + inString.length)
var regex = /(<([^>]+)>)/ig
var outString = inString.replace(regex, "");
console.log("No HTML sting " + outString);
if ( outString.length < maxlength){
callback(outString)
} else {
console.log("Lets cut first bit")
}
}
But then I started thinking, is there a way where I can control regex execution. So lets say that I want to keep certain tabs, like b,br,i and maybe change H1-6 to b. So in pseudo code, something like:
for ( var i in inString.regex.hits ) {
if ( hits[i] == H1 ) {
hits[i] = b;
}
}
The issue is that I want the text thats not HTML tags to stay as it is, and I want it to just cut out by default. One option would of course be to change the ones I want to keep. Say change <b> to [[b]], once that is done to all the ones of interest. Then put them back to <b> once all unknown have been removed. So like this (only for b, and not certain the code below would work):
function(inString, maxlength, callback){
console.log("Sting is " + inString)
console.log("Its " + inString.length)
var regex-remHTML = /(<([^>]+)>)/ig
var regex-hideB = /(<b>)/ig
var regex-showB = /([b])/ig
var outString = inString.replace(regex-hideB, "[b]");
outString = outString.replace(regex-remHTML, "");
outString = outString.replace(regex-showB, "<b>");
console.log("No HTML sting " + outString);
if ( outString.length < maxlength){
callback(outString)
} else {
console.log("Lets cut first bit")
}
}
But would it be possible to be smarter, writing cod ethat says here is a peice of HTML tag, run this code against the match.
As Tim Biegeleisen sai in its comment, maybe a better solution could be using a parser instead of a Regex...
By the way, if you want to control what is going to be changed by the regex you can pass a callback to the String.prototype.replace:
var input = "<div><h1>CIAO Bello</h1></div>";
var output = input.replace(/(<([^>]+)>)/gi, (val) => {
if(val.indexOf("div") > -1) {
return "";
}
return val;
})
;
console.log("output", output);
I'm trying to display some data in a <div> and IE9 is not keeping more than one carriage return. This works fine in Chrome, but not IE9 (it only adds the <br/>) Here's the code:
$.get(url,function(xml){
$("record",xml).each(function(){
var profile= $("profile",this).text().replace(/\r\n|\r|\n/g,'~').replace(/~~/g,'<\/p> <p>').replace(/~/g,'<br/>');
profileRpt += profile
});
});
Thought process on this was to normalize, then add <p> for double carriage returns and <br> for the single returns.
I've also tried the simple replacement,
var points= $("points",this).text().replace(/\n\r?/g, '<br />');
and again this worked fine in Chrome, but not in IE9.
Does anyone know of a way I can get this to work in IE9? Thanks!!
UPDATE
So it seems that jQuery is the culprit when used in IE, as it collapses the line breaks prior to any replace function.
Can anyone help with using an alternate (non-jQuery) method of retrieving the data from the xml response as I've done above? One that would preserve the line breaks?
Thanks for your help!
Try this:
function unifyLineFeeds = function(str) {
return str.replace("\r\n", "\n").replace("\r", "\n");
}
You can then use this function to output text as HTML following way:
// `text` var contains text with line ununified line feed characters.
text = unifyLineFeeds(text);
var lines = text.split("\n"),
count = lines.length,
lastIndex = count - 1;
var container = document.getElementById('someContainerToShowFormattedText');
for (var i = 0; i < count; i++) {
container.appendChild(document.createTextNode(lines[i]));
if (i < lastIndex) {
container.appendChild(document.createElement('br'));
}
}
var points = $("points", this).text().replace(/\r+/g, '').replace(/\n/g, '<br>');
I have got a div with words seprated by a comma. How can i arrange them so there is four words per line?
edit: the words are dynamically generated
Use the <pre>...</pre> tag. The text will appear on the screen exactly the way you have formatted it.
Using jQuery to simplify access to the DOM:
var content = $('#mydiv').text(); // get current content from the page
var words = content.split(','); // break into words
for (var i = 3; i < words.length; i += 4) { // every fourth word (but not the first)
words[i] += '<br>'; // append <br>
}
content = words.join(' '); // and rejoin with spaces
$('#mydiv').html(content); // and put it back in the page
NB: I've used .html() to write the contents back out otherwise the <br> tags won't be rendered properly.
Use the BR tag after every four words. See http://www.w3.org/wiki/Html/Elements/br
If str contains the words, then:
var lines = str.match(/([^,]+,*){1,4}/g);
var output = lines === null ? '' : lines.join('<br>');
Example
If:
str = "a,b,c,d,e,f,g,h,i";
Then output will be:
"a,b,c,d,<br>e,f,g,h,<br>i"
Demo here.
Using jQuery, everthing is easier. jQuery is a bunch of tools written in JavaScript and it is all saved to a variable called $. You can call jQuery which will call the base JavaScript for you and make life easier.
Add this to the <head> of your web page
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
Add id="arrange" to your div. If you don't like the word arrange, you can use any word you like. Make sure there are no spaces and only letters, numbers, underscores.
<div class="arrange">One two three four one two three four</div>
Add this anywhere after the div that has the text
<script type="text/javascript">
$('div.arrange').each(function () { // For each div with the class="arrange"
var words = this.innerHTML.split(/,/) // Get an array of all the words (separated by comma)
var newHTML = '' // We will add the new contents of the div here.
for(var i = 0; i < words.length; i++) { // For every word
if(i != 0) {// If this is not the first word
if(i % 4 == 0) { // If this is the fourth word
newHTML += '<br/>' // Add a <br/>
} else {
newHTML += ',' // Add a comma
}
}
newHTML += words[i] // Add the word
}
this.innerHTML = newHTML
})
</script>
In this case, I am using jQuery to loop through each div with class="arrange"
You can see a live example here: http://jsfiddle.net/gf5wD/
This example automatically includes jQuery and automatically adds the JavaScript to the end.
You will probably eventually want to save the jquery file to servers you control. The script tag in your head will call the jquery servers which means if their site goes down, yours gets messed up.
Greetings user521180 I got you and i think this code will help
function arrangeDiv() {
var div = document.getElementById('div');
var divinnerHTMLAry = div.textContent.split(' ');
div.innerHTML = "";
var divNewinnerHTML = '';
var count = 0;
for (var i = 0; i < divinnerHTMLAry.length; i++) {
if (divinnerHTMLAry[i] != "" && divinnerHTMLAry[i] != "\n") {
divNewinnerHTML += divinnerHTMLAry[i] + " ";
count += 1;
if (count == 4) {
divNewinnerHTML += "<br />";
}
}
}
div.innerHTML = divNewinnerHTML;
}
Regards :)
edit : this is a PHP solution
Maybe something like that should be able to make what you want.
$string = 'a, b, c, d, e, f';
$array = explode(',', $string,);
foreach($array as $key => $word) {
print trim($word);
if ($key % 4 == 0) {
print '<br />';
}
}
If you get your word in an other way, just arrange the code so you can skip the explode() function.
How to replace all HTML tags from <anything> to \n<anything> and </anything> to <anything>\n
var text = "<anything>welcome</anything><anything>Hello</anything>";
result
var text = "\n<anything>welcome</anything>\n\n<anything>Hello</anything>\n";
This code will help you (match all tags)
</?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)/?>
You can prettify xml without regex:
var text = "<anything>welcome</anything><anything>Hello</anything>";
var xml = new XML("<root>" + text + "</root>");
console.log(xml.children().toXMLString());
output:
<anything>welcome</anything>
<anything>Hello</anything>
Just don't parse HTML using regex. Read this: http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html
In JavaScript, you can turn HTML into DOM using the .innerHTML property, and after that you can use other DOM methods to traverse it.
Simple example (needs Firebug):
var div = document.createElement('div');
var html = '<p>foo <span>bar</span><br /></p>';
div.innerHTML = html;
function scan(node, depth)
{
depth = depth || 0;
var is_tag = node.nodeType == 1;
var self_contained = false;
if (is_tag) {
self_contained = node.childNodes.length == 0;
var tag_name = node.tagName.toLowerCase();
console.log('<' + tag_name + (self_contained ? ' /' : '') + '>', depth);
} else {
console.log(node.data);
}
for (var i = 0, n = node.childNodes.length; i < n; i++) {
scan(node.childNodes[i], depth + 1);
}
if (!self_contained && is_tag) {
console.log('</' + tag_name + '>', depth);
}
}
scan(div);
Output:
<div> 0
<p> 1
foo
<span> 2
bar
</span> 2
<br /> 2
</p> 1
</div> 0
You could also modify this to output attributes and use the depth argument for indentation.
Try this:
str.replace(/<(\/?)[a-zA-Z]+(?:[^>"']+|"[^"]*"|'[^']*')*>/g, function($0, $1) {
return $1 === "/" ? $0+"\n" : "\n"+$0;
})
Expanding on #Amarghosh's answer:
Assuming the HTML you are trying to parse is more complicated than your example (which I would guess it is) you may want to convert your HTML page into XHTML. This will allow you to use treat it as XML and do a number of things including:
Use an XSL to transform the data
Use .NET's extensive set of XML
libraries to extract and manipulate the data.
I have done this in the past with a free .NET library called SGML.
text = text.replace(/<(?!\/)/g, "\n<"); // replace every < (which are not followed by /) by \n<
I have a text area that I need to parse. Each new line needs to be pulled out and an operation needs to be performed on it. After the operation is done the operation needs to be run on the next line. This is what I have at the moment. I know the indexOf search won't work because it's searching character by character.
function convertLines()
{
trueinput = document.getElementById(8).value; //get users input
length = trueinput.length; //getting the length of the user input
newinput=trueinput; //I know this looks silly but I'm using all of this later
userinput=newinput;
multiplelines=false; //this is a check to see if I should use the if statement later
for (var i = 0; i < length; i++) //loop threw each char in user input
{
teste=newinput.charAt(i); //gets the char at position i
if (teste.indexOf("<br />") != -1) //checks if the char is the same
{
//line break is found parse it out and run operation on it
userinput = newinput.substring(0,i+1);
submitinput(userinput);
newinput=newinput.substring(i+1);
multiplelines=true;
}
}
if (multiplelines==false)
submitinput(userinput);
}
So for the most part it is taking the userinput. If it has multiply lines it will run threw each line and seperatly and run submitinput. If you guys can help me I'd be eternally thankful. If you have any questions please ask
Line breaks within the value of a textarea are represented by line break characters (\r\n in most browsers, \n in IE and Opera) rather than an HTML <br> element, so you can get the individual lines by normalizing the line breaks to \n and then calling the split() method on the textarea's value. Here is a utility function that calls a function for every line of a textarea value:
function actOnEachLine(textarea, func) {
var lines = textarea.value.replace(/\r\n/g, "\n").split("\n");
var newLines, i;
// Use the map() method of Array where available
if (typeof lines.map != "undefined") {
newLines = lines.map(func);
} else {
newLines = [];
i = lines.length;
while (i--) {
newLines[i] = func(lines[i]);
}
}
textarea.value = newLines.join("\r\n");
}
var textarea = document.getElementById("your_textarea");
actOnEachLine(textarea, function(line) {
return "[START]" + line + "[END]";
});
If user is using enter key to go to next line in your text-area you can write,
var textAreaString = textarea.value;
textAreaString = textAreaString.replace(/\n\r/g,"<br />");
textAreaString = textAreaString.replace(/\n/g,"<br />");
textarea.value = textAreaString;
to simplify the answers, here is another approach..
var texta = document.getElementById('w3review');
function conv (el_id, dest_id){
var dest = document.getElementById(dest_id),
texta = document.getElementById(el_id),
val = texta.value.replace(/\n\r/g,"<br />").replace(/\n/g,"<br />");
dest.innerHTML = val;
}
<textarea id="targetted_textarea" rows="6" cols="50">
At https://www.a2z-eco-sys.com you will get more than what you need for your website, with less cost:
1) Advanced CMS (built on top of Wagtail-cms).
2) Multi-site management made easy.
3) Collectionized Media and file assets.
4) ...etc, to know more, visit: https://www.a2z-eco-sys.com
</textarea>
<button onclick="conv('targetted_textarea','destination')" id="convert">Convert</button>
<div id="destination">Had not been fetched yet click convert to fetch ..!</div>