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.
Related
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>
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 am creating a live content editor for an element using textarea, but its output isn't like what the expected if the inputted value is symbol like > or < or mix up of those symbols and texts, instead of just texts, then it will not replacing instead of doubled it up.
Here is the Fiddle
And here is the jquery codes:
$("#changer").on("change keyup paste", function () {
// get current element
var thehtml = $("#tochange").html();
var thetext = $("#tochange").contents().filter(function () {
return this.nodeType === 3;
}).text().trim();
var thechange = $(this).val();
// if has element, then keep it, add text and put back
var thepurehtml = thehtml.replace(thetext, "");
var theoutput = thechange;
if ($.trim(thepurehtml) != '') {
var theoutput = thechange + thepurehtml;
}
$("#tochange").html("").html(theoutput);
return;
});
What's causing it and how to fix it up?
PS: I need to have the functionality of this line var theoutput = thechange + thepurehtml; because it is sometimes the edited element have html element other than just a blank or text node.
However i am going to delete this answer, As i don't have enough reputation to comment i am posting as answer.
So #SoursopTree, what you actually want to achieve?
What i found is when you enter < or > the line $.trim(thepurehtml) is returning empty string (null) and null!='', so the next statement var theoutput = thechange + thepurehtml; here thechange=> and thepurehtml=>. so you are getting two symbols instead of one.
You said you need to have the functionality of this line var theoutput = thechange + thepurehtml;
let´s say I have a string in JavaScript:
var str = '<span class="color:red;">Hello</span> my name is <span class="color:red;">Julian</span>';
So I would like to print each 300ms one character so that it looks as if it is being entered. Sure I can make a for-loop for each character and print it inside an element, but the problem is the formatting. If I use the for-loop it will even print the span-tag separately, but that will causing problems.
How to print every character after a while with formatting?
This quite an evil trick but you can use a white div on top of your string and move it step by step every 300ms. In this way a letter appears every 300ms. The only problem is to determine how big each step needs to be since the width of each character will vary.
A way to determine the width is to load all the characters separate in a div and measure the width. Of course you first need to strip the html. In order to so you could use How to strip HTML tags with jQuery?
You could split all characters into an array and then loop like this:
var str = '<span class="red">Hello</span> my name is <span class="red">Julian</span>',
AllChars = [],
SetTxt = true,
newstr = '';
for (var i = 0; i < str.length; i++) {
newstr += str.substr(i,1);
if((str.substr(i,1) == '<') || (str.substr(i,1) == '&')){
SetTxt = false;
}else if(SetTxt){
AllChars.push(newstr);
}else if((str.substr(i,1) == '>') || (str.substr(i,1) == ';')){
if(str.length == (i+1)){
AllChars.push(newstr);
}
SetTxt = true;
}
}
for (var i in AllChars){
setTimeout(function(i){
$('#text').html(AllChars[i]);
},300 * i,i);
}
Check the jsfiddle for a working example: http://jsfiddle.net/2R9Dk/1/
You need to parse html tags and text separately. Something like:
var str = '<span class="colored">Hello</span> my name is <span class="colored bold">Julian</span>';
function printTextByLetter(text, selector, speed) {
var html = text.match(/(<[^<>]*>)/gi),
sel = selector || 'body',
arr = text.replace(/(<[^<>]*>)/gi, '{!!}').match(/(\{!!\}|.)/gi),
counter = 0, cursor = jQuery(sel), insideTag,
interval = setInterval(printChar, speed);
function printChar() {
if(arr[0]){
if(arr[0] === '{!!}') {
if(!insideTag) {
insideTag = true;
cursor.append(html[0], html[1]);
html.shift();
html.shift();
cursor = cursor.children().eq(counter);
} else {
insideTag = false;
cursor = cursor.parent();
counter++;
}
} else {
cursor.append(arr[0]);
}
arr.shift();
} else {
clearInterval(interval);
}
}
}
// DOM ready
jQuery(function($){
printTextByLetter(str, '#target', 300);
});
And don't forget to clear intervals - it does affect performance.
Example on JSFiddle: http://jsfiddle.net/36kLf/7/
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<