Jquery use "count" instead of "slice" - javascript

My code is supposed to place a banner after x amount of words. The code is working, but not as it should, as it is using slice to make the counting or slicing.
I need to use (count >= 20) instead of slice(0, 20)
This way the words in the text will be counted, instead counting the lines.
This is the code that does what I need: https://jsfiddle.net/714Lmgfu/3/
However, there is a loop in this code, which replicates the image (As show in the Fiddle) and I was not able to make return false working.
So I got some help and this was the final result https://jsfiddle.net/scadp0ar/, this code is working the way it should, except that, as stated before, it doesn't count the words. What should I change to make it count the words instead?
For example, change:
var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
$(".newsitem_text").html(function (i, h) {
return h.replace(h.split(/\s+/).slice(0, 20).join(' '), function (m) {
return m + img; });
});
for:
function check() {
if (count >= 20) {
newHtml += '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
count = 0;
}
}

var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
$(".newsitem_text").html(function (i, h) {
// Match a word followed by one or more spaces 20 times
// Insert <img>-tag
// Repeat
return h.replace(/([^\s]+\s+){20}/g, function (m) {
return m + img;
});
});
Breakdown:
/ # Start regex
( # Start capturing group
[^\s]+ # Match everything - but space - 1 or more times
# could also be written as .+? that means:
# match everything 1 or more times, but not gready (meaning that if a space is encountered it will stop matching)
\s+ # Match space 1 or more times
) # End group
{20} # repeat 20 times
/ # End regex
g # global flag - will run the regex multiply times until no more matches are posible

Try using String.prototype.match() with RegExp /\w+./g to match alphanumeric character followed by any single character , Array.prototype.splice()
var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
var text = document.querySelector(".newsitem_text");
var html = text.innerHTML,
matches = html.match(/\w+./g);
matches.splice(20, 0, img);
text.innerHTML = matches.join(" ");
<div style="width:450px; margin-left:auto; margin-right:auto" class="newsitem_text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec pellentesque urna eu pulvinar maximus. Sed elit nunc, vestibulum ut eros vitae, pellentesque rhoncus ipsum. In et metus non diam porttitor maximus iaculis nec lectus. Quisque sodales scelerisque
auctor. Nam rutrum venenatis eros, eu condimentum erat placerat ut. Pellentesque sed tempus sem, eu viverra ipsum. Vestibulum nec turpis convallis, dapibus massa vitae, posuere mauris. Suspendisse mattis tincidunt lorem. Aliquam erat volutpat. Nullam
at tincidunt erat, maximus laoreet ipsum. Quisque nunc neque, semper tincidunt placerat eget, blandit a ante. Suspendisse pulvinar, velit eu ultrices pulvinar, lacus sapien tincidunt ipsum, eget sollicitudin mauris eros molestie ex. Etiam quis orci
dui. Phasellus vestibulum mollis molestie. Nam condimentum ornare nisl, sed finibus risus tempus vel. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum eget ullamcorper
lorem. Aliquam mollis elit in sem dapibus dapibus. Proin vel massa a arcu dictum tincidunt in ut ante. Sed feugiat tempus dictum. Praesent in leo ullamcorper, sodales turpis et, vehicula tellus. Duis pellentesque dui ac turpis tristique imperdiet. Sed
sed orci lectus. Suspendisse non egestas sem, sed tincidunt sem. Etiam laoreet dui sem. Mauris hendrerit massa tempus, euismod arcu sit amet, eleifend quam. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus
id fringilla mauris. Cras dapibus non lacus at finibus. Nullam vitae sagittis neque. Mauris libero velit, interdum non vehicula non, lacinia non augue. Maecenas elementum lacinia interdum. Morbi eget mollis nisl. Integer accumsan condimentum tellus,
lacinia pellentesque urna volutpat a. Nullam semper sem et erat commodo sollicitudin. Proin rhoncus felis eu aliquam venenatis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla pretium velit eu molestie
condimentum. Vestibulum vitae velit mi. Integer nec leo quam. Nam pulvinar ligula congue consectetur tristique. Donec placerat faucibus diam sit amet fermentum. Ut id pellentesque risus. Nunc lacus orci, rhoncus ut risus sed, mattis posuere tellus.
Nulla pellentesque eros sed neque consectetur dictum.</div>
jsfiddle https://jsfiddle.net/scadp0ar/3/

You should try something like this:
var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />';
jQuery( document ).ready(function( $ ) {
$(".newsitem_text").html(getTextWithImageBetweenWords($(".newsitem_text").html(),20));
});
function getTextWithImageBetweenWords(text, count){
var split_text = text.split(' ');
var _out = [];
var words = split_text.length;
for(var i=0;i < words; i++){
if(i !== 0 && i === count){
_out[i] = split_text[i] + img;
}
else{
_out[i] = split_text[i];
}
}
return _out.join(' ');
}
This is a more readable and easy way to accomplish this, here is the JSFiddle!
Note: if you want to repeat the image every n (20 in your case) words, just change i === count for i % count === 0.

From your comment, you may want to edit the question (just for clarity not trying to be a jerk). Also, by splitting at space, the count is of words. '\s' is space '\n' is new line '\t' is carriage return, '\r\n' is a special type of carriage return. You could potentially make a more complicated regex to cover everything that is not a new line or a space '\t|\s|\r\n'. To place the image within lines, you can use a styling trick as explained later.
If you want to have the image not repeat change:
function check() {
if (count >= 20) {
newHtml += '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
count = 0;
}
}
For an even nicer fit, try align="right" which will wrap the text around the image.
//jQuery(function ($) {
jQuery( document ).ready(function( $ ) {
var img = '<img align="right" src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
$(".newsitem_text").html(function (i, h) {
return h.replace(h.split(/\s+/).slice(20,21).join(' '), function (m) {
return m + img; });
});
});
to
function check() {
if (count == 20) {
newHtml += '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />';
}
}
To avoid using a nasty loop, you could slice at a different location or use splice:
//jQuery(function ($) {
jQuery( document ).ready(function( $ ) {
var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
$(".newsitem_text").html(function (i, h) {
return h.replace(h.split(/\s+/).slice(20, 21).join(' '), function (m) {
return m + img; });
});
});
To wrap your image within the words use align="left" or align="right" in the image tag.
<img align="right" src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />

Related

Create multidimensional arrays from a text box to compare and merge their details

I’ve been trying to compare a block of lines for a few days now and still haven't found a solution. Actually, it seems that I can't split an array in a multidimensional array. I’ll give you full details should anyone know a better solution and would like to share it.
I have an html page including a textbox where I load data I want to use. It calls several action in an external javascript file to show executed data in three spans, here is a demo:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="..\..\..\css\style.css">
<script type="text/javaScript" src="..\..\js\javaction.js"></script>
</head>
<body>
<span id='CHANGINGvalue'><textarea rows="4" cols="20" id="loadingTEXTboxDATA" name="saveIT" onkeyup="actionJAVA1(document.getElementById('CHANGINGvalue'));actionJAVA2(document.getElementById('CHANGINGvalue'));" value="">load data inside this text box</textarea><div class="tooltipRIGHT">🛈<span class="tooltiptext">load data inside this text box</span></div></br></span>
<span id='showAREAdata1'>sss</span><br><br>
<span id='showAREAdata2'>ccc</span><br><br>
<span id='showAREAdata3'>hhh</span><br>
</body>
</html>
This is my javaction.js file:
function actionJAVA1(val)
{
var startingDATA = val.value;
if (startingDATA.includes("text to trigger action")) {
// first block of text to search trough
var i= 0;
var bloccoPERlinee = val.value.split("\n");
for ( i = 0; i < bloccoPERlinee.length; ++i)
{
if (bloccoPERlinee[i].includes('specific text search 1'))
{
// Yes, it's there
}
else {
// block of code to be executed if the condition is false
bloccoPERlinee[i] = ""
}
}
var SBLOCCOlinee1 = bloccoPERlinee.join("\n");
const removeEmptyLines = SBLOCCOlinee1.split(/\r?\n/).filter(line => line.trim() !== '').join('\n');
var eSEfunzionaLOpotevoTROVAREprima = removeEmptyLines.split('\n').filter(function (s) { return s.match('filtering word to eclude') })
var l = 0;
for ( l = 0; l < eSEfunzionaLOpotevoTROVAREprima.length; ++l)
{
eSEfunzionaLOpotevoTROVAREprima[l] = eSEfunzionaLOpotevoTROVAREprima[l].split('permit');
eSEfunzionaLOpotevoTROVAREprima[l] = eSEfunzionaLOpotevoTROVAREprima[l][1]
}
var ANCORAnonSOgestireARRAYmultilinea = eSEfunzionaLOpotevoTROVAREprima.join("\n");
document.getElementById('showAREAdata1').innerText = ANCORAnonSOgestireARRAYmultilinea;
// second block of text to search trough
var x= 0;
var bloccoPERlinee2 = val.value.split("\n");
for ( x = 0; x < bloccoPERlinee2.length; ++x)
{
if (bloccoPERlinee2[x].includes('alternative text to search trough'))
{
// Yes, it's there
}
else {
// block of code to be executed if the condition is false
bloccoPERlinee2[x] = ""
}
}
var SBLOCCOlinee2 = bloccoPERlinee2.join("\n");
const removeEmptyLines2 = SBLOCCOlinee2.split(/\r?\n/).filter(line => line.trim() !== '').join('\n');
var senzaCOMMENTI = removeEmptyLines2.split("\n");
document.getElementById('showAREAdata2').innerText = senzaCOMMENTI;
So far so good: I correctly managed to find the data I want that mainly are numeric value occurring in a different format and details in both arrays coming out from first (array1 named ANCORAnonSOgestireARRAYmultilinea) and second filtering actions (array2 named senzaCOMMENTI).
Besides that I do expect that in array1 should be just one match for any line in array 2, I now should compare them and merge matching data to show in span "showAREAdata3".
I thought to split them getting multdimensional array and if any value show up in both lines from array1 and array2 I should add at line value from arra1 last value from matching line in array2.
I start declaring a clone from those array and then trying to split array1 value by line and by given characters that in this case is a slash / but I managed to make it work just one per time. At second split it stop to work and the whole java function crash.
On array2 which should be even easier since it already comes in an array and I just should split by blank space to get multidimensional array is actually worse: I can not do it: it also crash the whole java function.
That’s in the specific what I tried in this last case:
var senzaCOMMENTIa = structuredClone(senzaCOMMENTI);
var senzaCOMMENTIa = Array.from(senzaCOMMENTIa);
const myArray = senzaCOMMENTIa.split(" ");}}
I may think to use map or for each – and I also tried a few solutions but did not succeded.
In the comments Swiffy asked for an example of how the input and outputs should be:
text box : mult line pasted text from external source
[
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut velit eget arcu eleifend consequat. Suspendisse tempor ut tellus ut fermentum. Donec sed euismod felis. Fusce venenatis viverra metus quis elementum. Etiam diam sapien, dignissim eget auctor a, bibendum vel nulla. Morbi non vulputate quam. Ut commodo venenatis ultrices. Phasellus a diam ultricies, iaculis enim at, lobortis nibh. Proin sodales tristique quam. Vivamus ornare sollicitudin mi, nec tincidunt neque mollis eget. Vivamus fermentum cursus felis, id pulvinar magna semper non. Duis id eros in massa dictum maximus. Nullam mollis risus non ligula consectetur, vel interdum massa laoreet. Aliquam nec finibus ex.
Praesent pretium hendrerit urna in finibus. Sed lacus ex, pharetra sed leo sed, molestie ultricies turpis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum viverra fermentum. Donec tincidunt libero tortor. Pellentesque facilisis, urna id viverra volutpat, massa erat finibus urna, sit amet rutrum felis lectus eu ex. Maecenas tincidunt orci molestie turpis ullamcorper, non feugiat felis tempus. Fusce rutrum urna sit amet mattis suscipit. Aliquam non sem sollicitudin, lacinia orci sit amet, finibus nisi. Mauris sollicitudin massa non massa sollicitudin pellentesque. Duis finibus ipsum et molestie tempor.
Maecenas
line1dataA/line1dataB
tempus
line2dataC/line2dataD data3b
. Vestibulum
line3dataE/line3dataF
Sed efficitur lorem vitae orci
data1a data2a data 3a(occasional) data4a
tincidunt volutpat.
data1b data2b data3b
data1c data2c data3c(occasional) data3d
Sed volutpat velit ut neque varius gravida a et elit. Ut egestas diam in urna varius, at volutpat mi rutrum. Sed dictum venenatis arcu, sit amet maximus tellus egestas vitae. Sed condimentum orci ac dolor dictum cursus. Suspendisse et eros velit. Donec rhoncus purus ex, nec volutpat elit viverra a. Integer efficitur non nibh eget congue.
Interdum et malesuada fames ac ante ipsum primis in faucibus. Morbi hendrerit bibendum lectus, at convallis sem cursus vel. Aliquam nec sem scelerisque, tempor elit sed, lacinia augue. Duis ex ipsum, tempus non placerat non, eleifend maximus est. Suspendisse sodales nulla a quam euismod, in tincidunt elit venenatis. Cras interdum vitae felis at vestibulum. Integer ac est ultricies, tincidunt ipsum in, tempor eros. Vivamus ultrices massa eleifend viverra auctor.
]
while being the array I've already found fro array1 such as:
array1: [line1dataA/line1dataB
line2dataC/line1dataD,
line3dataE/line3dataF,
so on,]
and for array2 such as:
array2: [data1a data2a data 3a(occasional) data4a, data1b data2b data3b, data1c data2c data3c(occasional) data4c, so on]
result of comparision:
line1dataA/line1dataB data4a
line2dataC/line2dataD data3b
line3dataE/line3dataF data4c
so on

Javascript shorten string and find sentence end

I am trying to shorted long string by number of characters (approximately) and finding sentence end (dot). Obviously this is not going to be 100% correct in all cases but its good enough. So for example, shorted string to 250 characters and find nearest dot as sentence end.
So having this:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in neque. Vivamus tellus. Donec magna. Donec consequat hendrerit magna. In iaculis neque eget nisi. Maecenas vehicula, leo eu commodo aliquam, sem dolor iaculis eros, vel mollis sem urna ac sapien. Integer mattis dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est.
Would create this:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in neque. Vivamus tellus. Donec magna. Donec consequat hendrerit magna. In iaculis neque eget nisi. Maecenas vehicula, leo eu commodo aliquam, sem dolor iaculis eros, vel mollis sem urna ac sapien.
Things to consider I think:
If there is no dot in the string, shorten string by word boundary (so not to break a word) and add ellipsis (...) on the end which would be this function:
function truncateString( str, n, useWordBoundary ){
if (str.length <= n) { return str; }
var subString = str.substr(0, n-1);
return (useWordBoundary
? subString.substr(0, subString.lastIndexOf(' '))
: subString) + "...";
};
How could one incorporate dot finding into this function?
One approach you can make is splitting upp the string into chars in an array. Looping over the array from position 250 to position 0 and breaking when you find a dot. Take that index of the dot and splice the original array from the starting char, 0, to the dot which is the index value of that dot plus one as splice doesnt include the last value. Then turning that array into a string again.
let string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in neque. Vivamus tellus. Donec magna. Donec consequat hendrerit magna. In iaculis neque eget nisi. Maecenas vehicula, leo eu commodo aliquam, sem dolor iaculis eros, vel mollis sem urna ac sapien. Integer mattis dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est.";
let arrarOfChar = string.split(""); //turns string into array
let position = -1; //-1 indicates that no dot has been found
for(let i = 250 ; i >= 0 ; i--) { //loop from 250 to 0
if(arrarOfChar[i] == ".") { //if that char is equal to "."
position = i; //set the position value to that
break; //break the for loop
}
}
if(position > 0) { //only if we found a dot
let newShortArrayOfChar = arrarOfChar.slice(0,position+1); //shorten the array from 0 to the dot index
let finalString = ""; //this is the final string
for(let i = 0; i < newShortArrayOfChar.length ; i++) {
finalString += newShortArrayOfChar[i]; //loop over every char and add it to the string
}
}
else {
// position should be -1
//handle if no dot exists
}
One option would be to use a regular expression: search for n or fewer characters, ending in a ., and if that match fails (there are no dots within the desired substring), search for n or fewer characters, followed by a word character and a word boundary:
const input = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in neque. Vivamus tellus. Donec magna. Donec consequat hendrerit magna. In iaculis neque eget nisi. Maecenas vehicula, leo eu commodo aliquam, sem dolor iaculis eros, vel mollis sem urna ac sapien. Integer mattis dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est.`;
function truncateString( str, n, useWordBoundary ){
const pattern = new RegExp(`^(?:.{1,${n}}\\.` + (
useWordBoundary
? `|.{1,${n - 1}}\\w\\b)`
: ')'
));
const match = str.match(pattern);
if (match) return match[0];
else return 'Match failed';
}
console.log(truncateString(input, 70));
// first sentence is more than 50 characters long, so this fails:
console.log(truncateString(input, 50));
// unless you enable word boundaries:
console.log(truncateString(input, 50, true));
The regex pattern looks like:
^(?:.{1,50}\.|.{1,49}\w\b)
Breaking that down:
^ - Start of string
(?: - Non-capturing group that alternates between:
.{1,50}\. - 50 or fewer characters, followed by a ., or:
.{1,49}\w\b) - 49 or fewer characters, followed by a word character and a word boundary
Here is a pretty straightforward example that trims the string to 250 characters then walks backward looking for the first . if it doesn't find one then the entire 250 characters are returned and if it does it trims it to that .
var maxLength = 250;
function test() {
var input = document.getElementById('test').value;
var trimmed = input.substr(0, maxLength);
var i = trimmed.length;
while (i > 0) {
if (trimmed[i] == '.') {
break;
}
i--;
}
var endResult = i > 1 ? trimmed.substr(0, i + 1) : trimmed;
endResult += endResult.length < input.length ? ' ...' : '';
document.getElementById('output').innerHTML = endResult;
}
.boxsizingBorder {
width: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
<button onclick="test()">
test
</button>
<textarea id="test" class="boxsizingBorder" rows="5">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in neque. Vivamus tellus. Donec magna. Donec consequat hendrerit magna. In iaculis neque eget nisi. Maecenas vehicula, leo eu commodo aliquam, sem dolor iaculis eros, vel mollis sem urna ac sapien. Integer mattis dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est.</textarea>
<p id="output"></p>
I would suggest to add two more parameters to your function in order to express what the extreme limits are for the offset at which the string would be clipped.
So for instance, if n is 250, you could provide 200 as a minimum and maybe 270 as the ultimate maximum for the cut-off point.
Then here is how I would include the dot-break possibility:
function truncateString( str, min, n, max, useWordBoundary ){
if (str.length <= max) return str;
if (useWordBoundary) {
// Prefer to break after a dot:
var i = str.indexOf(".", n)+1; // Look forward
if (i < min || i > max) i = str.slice(0, n).lastIndexOf(".")+1; // ...or backward
if (i >= min) return str.slice(0, i); // No ellipsis necessary
// If dot-break is impossible, try word break:
i = str.indexOf(" ", n); // Look forward
if (i < min || i > max) i = str.slice(0, n).lastIndexOf(" "); // ...backward
if (i >= min) n = i; // Found an acceptable position
}
return str.substr(0, n) + " ...";
}
// Example:
var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in neque. Vivamus tellus. Donec magna. Donec consequat hendrerit magna. In iaculis neque eget nisi. Maecenas vehicula, leo eu commodo aliquam, sem dolor iaculis eros, vel mollis sem urna ac sapien. Integer mattis dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est.";
console.log(truncateString(str, 200, 250, 270, true));
console.log(truncateString(str, 200, 250, 255, true));

Creating an array to read the number of words in a line

Hi guys so i am doing an exercise and one of the questions has asked me to "Create an algorithm that puts words divided by space with a max 100 character line length" So basically there is an array of 1000 words or so and its suppose to put 100 words per line, and spaces don't count. It also says :
Given N words where N >= 1000
Create rows of words separated by spaces where row length >= 100
Once a word has been used it should be considered removed.
Add to a simple SPA
Now i have done this to the best of my ability but i created my own set of words, i was wondering how to change it to use an array and also how to remove it when its done been used. To be honset i am not sure what SPA means at all , so if someone can explain that, that would be fantastic.
const paragraph = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam nibh. Nunc varius facilisis eros. Sed erat. In in velit quis arcu ornare laoreet. Curabitur adipiscing luctus massa. Integer ut purus ac augue commodo commodo. Nunc nec mi eu justo tempor consectetuer. Etiam vitae nisl. In dignissim lacus ut ante. Cras elit lectus, bibendum a, adipiscing vitae, commodo et, dui. Ut tincidunt tortor. Donec nonummy, enim in lacinia pulvinar, velit tellus scelerisque augue, ac posuere libero urna eget neque. Cras ipsum. Vestibulum pretium, lectus nec venenatis volutpat, purus lectus ultrices risus, a condimentum risus mi et quam. Pellentesque auctor fringilla neque. Duis eu massa ut lorem iaculis vestibulum. Maecenas facilisis elit sed justo. Quisque volutpat malesuada velit.",
lines = Math.round(paragraph.length / 100);
let line = 0;
for (let i = 0; lines > i; i++) {
document.body.innerHTML += paragraph.slice(line, line + 100) + '<br>';
line += 100;
}
So i got it to go through my set of words and it worked fine but i just need to change it to use an array which is what i am trying to figure out
Thanks for all the help

Getting 3rd line of div content

I have a div with some content in four lines. I am able to get number of lines by using the following code. But my requirement is to get 4 line text of the div. For example:
<div>
ut returns between paragraphsut returns between paragraphs
ut returns between paragraphsut returns between paragraphs
web ui text is going on hereut returns between paragraphsut
returns between paragraphs
</div>
In the above DIV.I want to get 4th line text i.e., returns between paragraphs.Is there any way to do this.
I am getting number of lines with the following code
var content = elm.innerHTML;
var elmHeight = elm.offsetHeight;
var lineHeight = 15;
var lines = elmHeight / lineHeight;
lines variable has number of lines in a particular DIV
var line_number=3; // The line number you prefer
var result= $.trm( $( '#mydiv' ).text() ).split( '\n' )[line_number];// mydiv is the id of division
alert(result);
The following works in Firefox for me. I hope it could be adopted to work under IE as well.
<html>
<head>
<script language="javascript">
<!--
function find3rdline (element)
{
var text = element.textContent;
var begin = -1;
var end = -1;
var top = -1;
var line = -1;
for (i = 0; i < text.length; i++)
{
var id = "marker" + i;
element.innerHTML = text.substr (0, i) + "<span id='" + id + "'>X</span>" + text.substr (i, text.length - i);
var marker = document.getElementById (id);
if (marker.offsetTop != top)
{
top = marker.offsetTop;
line++;
if (line == 2) begin = i;
else if (line == 3)
{
end = i;
// break;
}
}
}
element.innerHTML = text;
if (begin == -1) return "";
else if (end == -1) return text.substr (begin, text.length - begin);
else return text.substr (begin, end - begin);
}
// -->
</script>
</head>
<body onload="alert ('Third line is: [' + find3rdline (text) + ']')">
<div id="text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce porttitor, leo non sollicitudin blandit, metus eros dapibus massa, nec euismod nunc sapien quis nunc. Maecenas mollis, justo sed egestas semper, nulla libero blandit sem, eget gravida ante sapien sagittis turpis. Vivamus sit amet elit tortor, a eleifend mi. Aliquam erat volutpat. Vestibulum sit amet pellentesque magna. Integer eget erat nisl. Suspendisse adipiscing placerat felis quis blandit. Etiam hendrerit tincidunt gravida. Nunc condimentum tristique commodo. Aliquam eget tellus et sapien accumsan cursus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce porttitor, leo non sollicitudin blandit, metus eros dapibus massa, nec euismod nunc sapien quis nunc. Maecenas mollis, justo sed egestas semper, nulla libero blandit sem, eget gravida ante sapien sagittis turpis. Vivamus sit amet elit tortor, a eleifend mi. Aliquam erat volutpat. Vestibulum sit amet pellentesque magna. Integer eget erat nisl. Suspendisse adipiscing placerat felis quis blandit. Etiam hendrerit tincidunt gravida. Nunc condimentum tristique commodo. Aliquam eget tellus et sapien accumsan cursus.
</div>
</body>
</html>

JS: Splitting a long string into strings with char limit while avoiding splitting words

I am trying to take a large block of text and split it into multiple strings that are 148 characters each, while avoiding cutting off words.
I have this now, which is splitting words:
var length = shortData.new.length;
if (length < 160){
outputString[0] = shortData.new;
document.write(outputString[0]);
}
if (length > 160 && length < 308){
outputString[0] = shortData.new.substring(0,148);
outputString[1] = shortData.new.substring(148,length);
document.write(outputString[0]+"(txt4more..)");
document.write(outputString[1]);
}
if (length > 308 && length < 468){
outputString[0] = shortData.new.substring(0,148);
outputString[1] = shortData.new.substring(148,308);
outputString[2] = shortData.new.substring(308,length);
document.write(outputString[0]+"(txt4more..)");
document.write(outputString[1]+"(txt4more..)");
document.write(outputString[2]);
}
if (length > 468 && length < 641){
outputString[0] = shortData.new.substring(0,148);
outputString[1] = shortData.new.substring(148,308);
outputString[2] = shortData.new.substring(308,468);
outputString[3] = shortData.new.substring(468,length);
document.write(outputString[0]+"(txt4more..)");
document.write(outputString[1]+"(txt4more..)");
document.write(outputString[2]+"(txt4more..)");
document.write(outputString[3]);
}
You can use this function, just pass in your string and the length and it will return the array, like:
var outputString = splitter(shortData['new'], 148);
The function:
function splitter(str, l){
var strs = [];
while(str.length > l){
var pos = str.substring(0, l).lastIndexOf(' ');
pos = pos <= 0 ? l : pos;
strs.push(str.substring(0, pos));
var i = str.indexOf(' ', pos)+1;
if(i < pos || i > pos+l)
i = pos;
str = str.substring(i);
}
strs.push(str);
return strs;
}
Example usage:
splitter("This is a string with several characters.\
120 to be precise I want to split it into substrings of length twenty or less.", 20);
Outputs:
["This is a string","with several","characters. 120 to",
"be precise I want","to split it into","substrings of",
"length twenty or","less."]
You are going to have to pad some of your strings, to make them have the number of characters you require.
var lines= s.match(/(.{1,147}\s)\s*/g);
You could use lastIndexOf() on a substr() of length 148 to find where to break the original string, remove that and loop while the length is > 148, like this:
var myText = "ad aenean adipiscing elit eget eleifend phasellus aenean lobortis vero venenatis ultricies eget iaculis ac neque nibh dignissim eleifend erat et in in justo sollicitudin mattis maecenas purus quis mi sed molestie integer magna non hendrerit nulla id neque augue suspendisse in in eget consectetuer et cubilia eu ullamcorper morbi elementum sed sed pharetra quam velit ante pellentesque eros nullam lobortis lorem fringilla libero elit nonummy purus sodales mauris sagittis praesent aenean in ut nullam ultricies quam aliquam arcu quisque semper lacinia lacinia sodales imperdiet ante venenatis suspendisse amet ante tellus nec nibh lorem in viverra magna cursus elit erat lobortis mattis purus pellentesque velit pellentesque dolor quam id mauris nibh pellentesque augue vel posuere aptent varius vivamus parturient hac ligula libero a varius sollicitudin sed dictumst morbi eros vestibulum donec purus turpis urna vel nisl quisque vulputate tristique non sed risus viverra varius tincidunt hendrerit ac dui mollis quam nunc suspendisse mattis volutpat vulputate integer ipsum cursus erat justo eu vestibulum sed blandit ac mi ligula montes sollicitudin vitae vel lacus imperdiet orci tincidunt sed imperdiet nunc vehicula pellentesque orci gravida diam non ut wisi sit et massa congue id scelerisque et mauris arcu nunc litora dignissim urna ea nullam magna felis duis pellentesque ultricies tincidunt vel pede fusce nunc sed interdum cursus wisi qui pulvinar wisi consectetuer fames sed hendrerit vitae velit viverra malesuada eu magna vehicula vivamus augue sagittis curabitur rutrum fringilla vivamus nisl enim eros elit vestibulum duis et duis erat sit auctor ac ipsum in et lacinia eu magna accumsan in nulla a sed massa maecenas ultricies duis dignissim sem augue id posuere lacus felis nisl quam ultricies urna dui curabitur morbi ante ut est eget tellus pulvinar mollis elementum tellus malesuada sollicitudin ligula fusce eget libero metus cras ligula felis nunc porttitor sit at";
var MAX_LENGTH = 148;
while (myText.length > MAX_LENGTH) {
var s = myText.substr(0, MAX_LENGTH);
var i = s.lastIndexOf(" ");
alert(myText.substr(0, i));
myText = myText.substr(i + 1, myText.length);
}
alert(myText);
Without thinking to much about it, I would do something like this, just not in pseudo code
if string length > 148
for i=148;i<string length;i+148
if character at i = space
add substring(i-148 to i) to output[]
else
add substring(i-148 to lastindoxof space) to output[]
set i to lastindoxof space + 1)
if i-148 != string length
add substring (i-148 to string length -1) to output[]

Categories