I have this in a Div (Text actually "wraps" because Div box has short width; except where line breaks are intentional):
"Now is the time
for all good men
to come to the aid
of their country"
"The quick brown fox
jumps over the
lazy dogs"
I would like this:
lazy dogs"
jumps over the
"The quick brown fox"
of their country"
to come to the aid
for all good men
"Now is the time
I've tried using Reverse(); but am not getting the desired results.
Note: I'm not trying to reverse a string per say, but actual lines of text (ie: sentences).
If you got line breaks like this \n, you can do the following:
var lineBreak = "\n",
text = "Now is the time\nfor all good men\nto come to the aid\nof their country";
text = text.split(lineBreak).reverse().join(lineBreak);
If the line break is another sign, change the variable lineBreak.
OK, got it eventually. Based on this answer of mine, I came up with a code that identifies the actual lines inside textarea, even when wrapped.
Next step was to translate div into textarea so we can use the above trick.
Having this, it's simple matter of manipulating the lines using .reverse() method.
Final code is:
$("#btnInvert").click(function() {
var placeholder = $("#MyPlaceholder");
if (!placeholder.length) {
alert("placeholder div doesn't exist");
return false;
}
var oTextarea = $("<textarea></textarea>").attr("class", placeholder.attr("class")).html(placeholder.text());
oTextarea.width(placeholder.width());
//important to assign same font to have same wrapping
oTextarea.css("font-family", placeholder.css("font-family"));
oTextarea.css("font-size", placeholder.css("font-size"));
oTextarea.css("padding", placeholder.css("padding"));
$("body").append(oTextarea);
//make sure we have no vertical scroll:
var rawTextarea = oTextarea[0];
rawTextarea.style.height = (rawTextarea.scrollHeight + 100) + "px";
var lines = GetActualLines(rawTextarea);
var paragraphs = GetParagraphs(lines).reverse();
lines = [];
for (var i = 0; i < paragraphs.length; i++) {
var reversedLines = paragraphs[i].reverse();
for (var j = 0; j < reversedLines.length; j++)
lines.push(reversedLines[j]);
if (i < (paragraphs.length - 1))
lines.push("");
}
rawTextarea.value = lines.join("\n");
placeholder.html(rawTextarea.value.replace(new RegExp("\\n", "g"), "<br />"));
oTextarea.remove();
});
function GetParagraphs(lines) {
var paragraphs = [];
var buffer = [];
$.each(lines, function(index, item) {
var curText = $.trim(item);
if (curText.length === 0) {
if (buffer.length > 0) {
paragraphs.push(buffer);
buffer = [];
}
} else {
buffer.push(curText);
}
});
if (buffer.length > 0)
paragraphs.push(buffer);
return paragraphs;
}
function GetActualLines(oTextarea) {
oTextarea.setAttribute("wrap", "off");
var strRawValue = oTextarea.value;
oTextarea.value = "";
var nEmptyWidth = oTextarea.scrollWidth;
var nLastWrappingIndex = -1;
for (var i = 0; i < strRawValue.length; i++) {
var curChar = strRawValue.charAt(i);
if (curChar == ' ' || curChar == '-' || curChar == '+')
nLastWrappingIndex = i;
oTextarea.value += curChar;
if (oTextarea.scrollWidth > nEmptyWidth) {
var buffer = "";
if (nLastWrappingIndex >= 0) {
for (var j = nLastWrappingIndex + 1; j < i; j++)
buffer += strRawValue.charAt(j);
nLastWrappingIndex = -1;
}
buffer += curChar;
oTextarea.value = oTextarea.value.substr(0, oTextarea.value.length - buffer.length);
oTextarea.value += "\n" + buffer;
}
}
oTextarea.setAttribute("wrap", "");
return oTextarea.value.split("\n");
}
Just put the actual ID of your div and it should work.
Live test case.
warning, this is pseudo code :
lines=[];
index=0;
start=0;
for(characters in alltext){
if(newLine){
lines.push(alltext.substring(start,index);
start=index;
}
i++
}
sortedLines=[]
for(var i=lines.length;i>-1;i--){
sortedLines.push(lines[i]);
html=$('selector').html();
html+=lines[i];
$('selector').append(html);
}
better use split
Related
I've seen similar questions asked on Stack Overflow regarding this topic, but I haven't seen anything specific that would help me. My issue is that I can't seem to figure out how to replace a dash in hiddenWord with a correctly guessed letter while still retaining the dashes for un-guessed letters. Here is what I have so far and I'm not even sure if it's on the right track.
<script type="text/javascript">
// Declaration of Variables
var wordPool= ["Alf", "MarriedWithChildren", "Cheers", "MASH", "CharlesInCharge", "FmailyTies", "KnightRider", "MagnumPI", "MiamiVice"];
var lives = 6;
var myLetter;
var letter;
var wordChoice;
var hiddenWord;
var i;
var enter;
// Selects word randomly from wordPool[]. Then replaces the letters with "- ".
function selectedWord() {
var number = Math.round(Math.random() * (wordPool.length - 1));
wordChoice = wordPool[number];
for(i = 0; i < wordChoice.length; i++){
hiddenWord = wordChoice.replace(/./g,"- ");
}
console.log(hiddenWord);
}
// Gives myLetter a value of key pressed. If key is "Enter" selectedWord() initiates
document.onkeyup = function(event) {
var myLetter = event.key;
if(myLetter === "Enter"){
selectedWord();
}
console.log(myLetter);
}
</script>
I have seen some stuff with jQuery and PHP but I have to do it in javascript for class. Any help would be appreciated and if this has been addressed before please let me know.
You can check each character at the word string, compare it with the chosen character and replace it, if it is the same character.
I changed your code a bit to reflect what you are looking for.
Also make sure to lowercase all characters to make it easier for the player.
// Declaration of Variables
var wordPool= ["Alf", "MarriedWithChildren", "Cheers", "MASH", "CharlesInCharge", "FmailyTies", "KnightRider", "MagnumPI", "MiamiVice"];
var lives = 6;
var myLetter;
var letter;
var wordChoice;
var hiddenWord;
var i;
var enter;
// Change character to selected one
function checkCharacter(n) {
for(i = 0; i < wordChoice.length; i++){
console.log(wordChoice[i].toLowerCase() + "==" + n);
if(wordChoice[i].toLowerCase() == n.toLowerCase()){
hiddenWord = setCharAt(hiddenWord,i,n);
}
}
console.log("[" + hiddenWord + "]");
}
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
// Selects word randomly from wordPool[]. Then replaces the letters with "- ".
function selectedWord() {
var number = Math.round(Math.random() * (wordPool.length - 1));
wordChoice = wordPool[number];
hiddenWord = wordChoice.replace(/./gi,"-");
console.log(wordChoice + "[" + hiddenWord + "]");
}
// Gives myLetter a value of key pressed. If key is "Enter" selectedWord() initiates
document.onkeyup = function(event) {
var myLetter = event.key;
if(myLetter === "Enter"){
if(lives == 0){
selectedWord();
lives = 6;
}else{
lives--;
}
}
console.log(myLetter);
checkCharacter(myLetter);
}
//Select a random word at start
selectedWord();
I made a JSfiddle that is working and playable:
Check it out here...
Try
hiddenWord += "- "
Instead of replace
Or
hiddenWord += wordChoice[i].replace(/./g,"- ");
Here's an example:
var word = "do this";
var displayWord = [];
for (var i = 0; i < word.length; i++) {//build array
if (word[i] === " ") {
displayWord.push(" ");
} else {
displayWord.push("-");
}
}
function update(userGuess) {//update array
for (var i = 0; i < word.length; i++) {
if (word[i] === userGuess) {
displayWord[i] = userGuess;
} else {
displayWord[i] = displayWord[i];
}
}
}
//Guess letters
update("h");
update("o");
displayWord = displayWord.join('');//convert to string
alert(displayWord);
Check out the pen - https://codepen.io/SkiZer0/pen/VbQKPx?editors=0110
I am trying to replace ` ticks with html code in a string.
var str = "this `code` and `here`"
my expected output
"this code and here"
What i am trying to do is below
.
get the positions with ticks in a string
replace those ticks with span html based on odd and even occurence.
not sure, i couldnt get expected and my browser gets hang. and
when i debug it. i see there is no index for string to replace.
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
var pos = [];
for (var i = 0; i < str.length; i++) {
if (str[i] === "`") {
pos.push(i);
}
}
if (pos.length > 1) {
for (var j = pos.length; j > 0; j--) {
var index = pos[j];
var spanHtml = '';
if (j % 2 == 0) {
spanHtml = "<span class='code'>"
} else {
spanHtml = "</span>";
}
str = str.replaceAt(index, spanHtml);
}
}
You can use String.prototype.replace() with RegExp
/(`\w+`)/g
String.prototype.slice() with parameters 1, -1 to slice string within backtick
`
characters
var str = "this `code` and `here`";
var res = str.replace(/(`\w+`)/g, function(match) {
return "<span class='code'>" + match.slice(1, -1) + "</span>"
});
document.body.insertAdjacentHTML("beforeend", res);
.code {
background: turquoise;
}
scope of var i is wider then you think, so pos.push(i) will have them all same at the end
replaceAt appends incorrect ending
replaceAt shifts rest of the string invalidating positions you found
I believe you wanted something along these lines:
var str = "this `code` and `here`"
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+1);
}
var pos = [];
var count = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] === "`") {
var index = i;
var spanHtml = '';
if (count % 2 == 0) {
spanHtml = "<span class='code'>"
} else {
spanHtml = "</span>";
}
count++;
str = str.replaceAt(index, spanHtml);
i+= spanHtml.length -1; // correct position to account for the replacement
}
}
console.log(str)
Use the JavaScript replace method.
var str = "this `code` and `here`";
var newStr = str.replace("`", "");
HTML Code
<textarea id="test"></textarea>
<button id="button_test">Ok</button>
Javascript
$(document).ready(function()
{
$("#test").val("123e2oierhqwpoiefdhqwopidfhjcospid");
});
$("#button_test").on("click",function()
{
var as=document.getElementById("test").value;
console.log(as);
});
We can get the values from textarea line by line using val and split functions. But
Is it possible to get the value from textarea line by line for very long word?.In the example i need to get the output as 123e2oierhqwpoiefdhqwo and pidfhjcospid as separate values.
Jsfiddle link here
You can use something like this. This will insert line breaks into into the textarea.
Credits: https://stackoverflow.com/a/4722395/4645728
$(document).ready(function() {
$("#test").val("123e2oierhqwpoiefdhqwopidfhjcospid");
});
$("#button_test").on("click", function() {
ApplyLineBreaks("test");
var as = document.getElementById("test").value;
console.log(as);
});
//https://stackoverflow.com/a/4722395/4645728
function ApplyLineBreaks(strTextAreaId) {
var oTextarea = document.getElementById(strTextAreaId);
if (oTextarea.wrap) {
oTextarea.setAttribute("wrap", "off");
} else {
oTextarea.setAttribute("wrap", "off");
var newArea = oTextarea.cloneNode(true);
newArea.value = oTextarea.value;
oTextarea.parentNode.replaceChild(newArea, oTextarea);
oTextarea = newArea;
}
var strRawValue = oTextarea.value;
oTextarea.value = "";
var nEmptyWidth = oTextarea.scrollWidth;
var nLastWrappingIndex = -1;
for (var i = 0; i < strRawValue.length; i++) {
var curChar = strRawValue.charAt(i);
if (curChar == ' ' || curChar == '-' || curChar == '+')
nLastWrappingIndex = i;
oTextarea.value += curChar;
if (oTextarea.scrollWidth > nEmptyWidth) {
var buffer = "";
if (nLastWrappingIndex >= 0) {
for (var j = nLastWrappingIndex + 1; j < i; j++)
buffer += strRawValue.charAt(j);
nLastWrappingIndex = -1;
}
buffer += curChar;
oTextarea.value = oTextarea.value.substr(0, oTextarea.value.length - buffer.length);
oTextarea.value += "\n" + buffer;
}
}
oTextarea.setAttribute("wrap", "");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="test"></textarea>
<button id="button_test">Ok</button>
Use .match(/pattern/g). As your OP ,pattern should start \w (Find a word character) and match string sequence {start,end}
$("#button_test").on("click",function()
{
var as=document.getElementById("test").value;
console.log(as.match(/(\w{1,22})/g));
});
If you made the textarea width fixed using css you could do this:
css
textarea { resize: vertical; }
javascript
$("#button_test").on("click",function(){
var as=document.getElementById("test").value;
var len = document.getElementById("test").cols;
var chunks = [];
for (var i = 0, charsLength = as.length; i < charsLength; i += len) {
chunks.push(as.substring(i, i + len));
}
console.log(chunks);
});
This is probly not the best way, but it works and i hope it could help you.
First thing, i found the textarea allow 8px for default fontsize charactere.
Exemple :
Textarea with 80px
=> Allow line with 10 char maximum, all other are overflow on new line.
From this you can do a simple function like this :
$("#button_test").on("click",function()
{
console.clear();
var length_area = $("#test").width();
var length_value = $("#test").val().length;
var index = Math.trunc(length_area/8);
var finalstr = $("#test").val().substring(0, index) + " " + $("#test").val().substring(index);
console.log(finalstr);
});
Here the JSFiddle
The <textarea> element has built in functionality to control where words wrap. The cols attribute can be set (either harded coded in the HTML or set with the .attr() method using jQuery). The attribute extends the text area horizontally and it also automatically wraps text at the set value.
Example jsFiddle
$("#test").val("123e2oierhqwpoiefdhqwopidfhjcospid");
var newString = $("#test").val().toString();
var splitString = parseInt($("#test").attr("cols"), 10) + 1;
var stringArray = [];
stringArray.push(newString);
var lineOne = stringArray[0].slice(0, splitString);
var lineTwo = stringArray[0].slice(splitString);
var lineBreakString = lineOne + "\n" + lineTwo;
console.log(lineTwo);
$('#test').after("<pre>" + lineBreakString + "</pre>");
$("#test").val("123e2oierhqwpoiefdhqwopidfhjcospid");
var newString = $("#test").val().toString();
var splitString = parseInt($("#test").attr("cols"), 10) + 1;
var stringArray = [];
stringArray.push(newString);
var lineOne = stringArray[0].slice(0, splitString);
var lineTwo = stringArray[0].slice(splitString);
var lineBreakString = lineOne + "\n" + lineTwo;
$('#test').after("<pre>" + lineBreakString + "</pre>");
//console.log(lineBreakString);
pre {
color: green;
background: #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<textarea id="test" cols='21'></textarea>
<button id="button_test">Ok</button>
The example addresses the specific question asked. If you want to deal with larger blocks of text, you should use the .each() method and for loops to iterate over each line break.
Documentation:
.slice()
textarea
.push()
.parseInt()
.attr()
var a = document.querySelectorAll('.post .content div');
var b = a[7].childNodes;
for(i=0;i<b.length;i++){
var exp = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|])/ig;
if(b[i].nodeType === 3){
var ahref = document.createElement('a');
ahref.className="easyBBurlFetch";
ahref.href=b[i].nodeValue.replace(exp,'$1');
ahref.innerText=b[i].nodeValue.replace(exp,'$1');
b[i].parentNode.insertBefore(ahref,b[i]);
b[i].parentNode.removeChild(b[i].nextSibling);
}
}
Someone gave me the answer as I had this code though it wasn't working correct. Though I have the issue now if my text is like so:
This is just a test so click here www.youtube.com which then becomes
www.youtube.com%20which%20then%20becomes
It doesn't event keep the first line of text, I just need to parse the url while keeping the surrounding text.
In need the output to save the actual surrounding text but parse the urls that are inside the text to html anchor tags <a> so that they can then be clickable and actually follow through to a real website and not have unnessarcy text inside it from what my user was writing about. Thank you
UPDATE
I've got closer to making this work-- But I'm having a problem with the first text in the string is saying Undefined I've been debugging this and can't seem to figure out why this is happening. Here is code
var a = document.querySelectorAll('.post');
var b = a[0].childNodes;
var textArray;
var ahref;
for (i = 0; i < b.length; i++) {
var exp = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|])/ig;
if (b[i].nodeType === 3) {
var newHTML;
textArray = b[i].textContent.split(" ");
for (var j = 0; j < textArray.length; j++) {
if (textArray[j] !== "" && validURL(textArray[j])) {
ahref = document.createElement('a');
ahref.href = (/^(http:\/\/|https:\/\/)/).test(textArray[j]) ? textArray[j] : "http://" + textArray[j];
ahref.innerText = textArray[j];
ahref.className = "easyURLparse";
textArray[j] = ahref;
}
newHTML+= textArray[j].outerHTML ? textArray[j].outerHTML + " " : textArray[j] + " ";
}
var div = document.createElement('div');
div.innerHTML = newHTML;
newHTML = "";
b[i].parentNode.insertBefore(div, b[i]);
b[i].parentNode.removeChild(b[i].nextSibling);
}
}
function validURL(str) {
var pattern = new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+#)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?");
if (!pattern.test(str)) {
return false;
} else {
return true;
}
}
Testing Code
Just need to figure out the undefined and why it's adding it
this regexp will do the job
exp = /href="(\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|])"/ig;
var a = document.querySelectorAll('.post');
var b = a[0].childNodes;
var textArray;
var ahref;
for (i = 0; i < b.length; i++) {
var exp = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|])/ig;
if (b[i].nodeType === 3) {
var newHTML;
if (validURL(b[i].textContent)) {
textArray = b[i].textContent.split(" ");
for (var j = 0; j < textArray.length; j++) {
if (textArray[j] !== undefined && textArray[j] !== "" && validURL(textArray[j]) && textArray[j] !== null) {
ahref = document.createElement('a');
ahref.href = (/^(http:\/\/|https:\/\/)/).test(textArray[j]) ? textArray[j] : "http://" + textArray[j];
ahref.innerText = textArray[j];
ahref.className = "easyURLparse";
textArray[j] = ahref;
}
newHTML += textArray[j].outerHTML ? textArray[j].outerHTML + " " : textArray[j] + " ";
}
var div = document.createElement('div');
div.innerHTML = newHTML;
div.className = "easyDiv";
b[i].parentNode.insertBefore(div, b[i]);
b[i].parentNode.removeChild(b[i].nextSibling);
}
newHTML = "";
}
}
function validURL(str) {
var pattern = new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+#)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?");
if (!pattern.test(str)) {
return false;
} else {
return true;
}
}
By taking the textNodes and splitting them into an array I can then change the url into an html element. Then taking the array elements seeing if there is outerHTML or not then placing it in a new string and replacing that textNode now with a workable link.
Working example
I am making a script which receives a String and separate it on smaller Strings.
Ex: "This is a long sentence, and I will separate it into smaller parts. Lalala"
It will return "This is a long sentence","and I will separate it into smaller parts","Lalala"
The aim of this is to use Google translator to transform text to speech, but this feature has a limit of about 70-80 chars, so if the string is too large I need to chop it.
First I chop in sentences separated by a dot ("."), then if there are still too long sentences, I split them with the commas (",") and if there are still too long strings I separate them in unique words.
Everything works well until I try to join some words so the audio become more continuous. For some reason the strings separated by commas get joined again. I do not know why.
This is the code:
Edit: Relevant section split out and formatted
function talk(text){
var audios = document.createElement('audio');
audios.setAttribute('id','audio_speech');
var playlist = new Array()
if(text.length >= 75) {
playlist = text.split(".");
for (var i = 0;i<playlist.length;i++) {
if (playlist[i].length >= 75) {
auxarr = playlist[i].split(",");
//alert(auxarr.length);
for(var j=0;j<auxarr.length;j++) {
auxarr2 = auxarr[j].split(" ");
document.write(auxarr2+"<br>");
if (auxarr[j].length >= 75) {
auxarr2 = auxarr[j].split(" ");
for(var x=0; x < auxarr2.length; x++){
if(auxarr2[x].length < 50) {
aux = auxarr2[x];
while (aux.length < 50 && auxarr2[x+1]) {
aux = aux + " " + auxarr2[x+1];
auxarr2.splice(x,1);
auxarr2[x]=aux;
}
}
//...
Edit: Full original code
function talk(text)
{
var audios = document.createElement('audio');
audios.setAttribute('id','audio_speech');
var playlist = new Array()
if(text.length >= 75) {
playlist = text.split(".");
for (var i = 0;i<playlist.length;i++) {
if (playlist[i].length >= 75) {
auxarr = playlist[i].split(",");
//alert(auxarr.length);
for(var j=0;j<auxarr.length;j++) {
auxarr2 = auxarr[j].split(" ");
document.write(auxarr2+"<br>");
if (auxarr[j].length >= 75) {
auxarr2 = auxarr[j].split(" ");
for(var x=0; x < auxarr2.length; x++){
if(auxarr2[x].length < 50) {
aux = auxarr2[x];
while (aux.length < 50 && auxarr2[x+1]) {
aux = aux + " " + auxarr2[x+1];
auxarr2.splice(x,1);
}
auxarr2[x]=aux;
}
}
auxarr_end = auxarr.slice(j+1,auxarr.length);
auxarr_begin = auxarr.slice(0,j);
document.write("<br>"+auxarr+"<br> aca");
document.write("<br>"+auxarr_end+"<br> aca1");
document.write("<br>"+auxarr_begin+"<br> aca2");
auxarr.splice(j,1);
auxarr_begin = auxarr_begin.concat(auxarr2);
j = auxarr.length;
auxarr = auxarr_begin.concat(auxarr_end);
alert(auxarr);
}
}
//alert("current: "+playlist[i]);
//alert("current length:"+playlist[i].length);
//alert("auxarr: "+auxarr);
playlist_end = playlist.slice(i+1,playlist.length);
playlist_begin = playlist.slice(0, i);
playlist.splice(i,1);
playlist_begin = playlist_begin.concat(auxarr);
i = playlist.length;
playlist = playlist_begin.concat(playlist_end);
//alert("new "+playlist[i]);
}
}
/*do {
textAux = text.substring(0, 74);
text = text.substring(textAux.length, text.length);
playlist.push(textAux);
}while(text.length >= 75);*/
} else {
playlist.push(text);
}
//
//playlist.push(text);
/*for(var a=0; a<playlist.length;a++){
document.write(playlist[a]+"<br>");}*/
audios.setAttribute('src', 'http://translate.google.com/translate_tts?tl=es&q=' + encodeURIComponent(playlist[0]));
playlist.splice(0,1);
audios.load();
audios.play();
/*
*/
audios.addEventListener('ended', function(){
if (playlist[0]){
audios.setAttribute('src', 'http://translate.google.com/translate_tts?tl=es&q=' + encodeURIComponent(playlist[0]));
playlist.splice(0,1);
audios.play();
}
}, false);
}
</script>
Try this, modify it to work with your constants and parameters.
var LIMIT = 20;
var res = new Array()
//strats with spliting by dot
var dotArr = "This is a long sentence. and I will separate it into smaller parts. Lalala".split(/[.]/);
for (var i = 0; i < dotArr.length; i++) {
if (dotArr[i].length > LIMIT){
//only when have to, split by comma
var comArr = dotArr[i].split(/[,]/);
for (var j = 0; j < comArr.length; j++) {
//only when have to and that a space exists, split by space
if (comArr[j].length > LIMIT && comArr[j].indexOf(" ") != -1 ){
var spaceArr = comArr[j].split(/[ ]/);
//accomulate words until we reach the limit and then push the value to res
for (var k = 0; k < spaceArr.length;){
var sMerge = spaceArr[k++];
while (k < spaceArr.length && sMerge.length + spaceArr[k].length + 1 < LIMIT){
sMerge = sMerge + " " + spaceArr[k];
k++;
}
res.push(sMerge)
}
}else{
res.push(comArr[j]);
}
}
}else{
res.push(dotArr[i]);
}
}
//res contain all optimized sentences.