Javascript Hangman - Replace Character In String - javascript

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

Related

Highlight the textContent or innerText of an element containing other elements also based on user's searchedWords Using Pure Javascript

How to highlight all the words that the user is searching without affecting the text of the display and the attributes inside the elements. I have tried some approaches but there is a problem as described below. Please help. Thank you. Keep safe and healthy.
<input type='text' id='search' onkeyup="highlight(this.value)">
<p id='WE1'><b>WE</b>wE & theythem and We<span id="we2">we only.</span></p>
function highlight(searchedWords) {
var p = document.getElementById("WE1");
var words = searchedWords.trim().split(" ");
for (var i=0; i < words.length; i++) {
var word = words[i].trim();
/*
searchedWords = "We Only";
trial#1: use replaceAll
p.innerHTML = p.innerHTML.replaceAll(word, "<mark>" + word + "</mark>");
Issues:
1) replaceAll does not work in other browsers
2) It highlights also the tag attributes containing the searchedWords
3) It is case sensitive, it only highlights the exact match, though I've addressed this using this:
var str = p.innerHTML;
for (var j=0; j < words.length; j++) {
var x = words[j].trim(), string = str.toLowerCase();
while (string.lastIndexOf(x) > -1) {
str = str.substring(0, string.lastIndexOf(x)) + "<mark>"
+ str.substr(string.lastIndexOf(x), words[j].length) + "</mark>"
+ str.substring(string.lastIndexOf(x) + words[j].length, str.length);
string = string.substring(0, string.lastIndexOf(x));
}
}
p.innerHTML = str;
4) Changing .toLowerCase() also changes the display to lower case
var x = p.innerHTML.toLowerCase, word = word.toLowerCase;
p.innerHTML = x.replaceAll(word, "<mark>" + word + "</mark>");
trial#2:
p.innerHTML = p.innerHTML.replace(new RegExp(words[i], "gi"), (match) => `<mark>${match}</mark>`);
Issues:
1) OK, it is NOT case sensitive, it highlights all the searchedWords and the display is OK
2) But, it highlights also the tag attributes containing the searchedWord, anchor tags are affected
I tried also using p.childNodes, nodeValue, textContent so that the attributes
containing the searchedWord are not affected yet it only inserts the words
<mark>SearchedWord</mark> and the searchedWord is not highlighted.
*/
}
}
replaceAll is a new feature es2021. As for today it's incompatible with IE.
I found you something that might work. Please have a look and tell me if you still have problems How to replace all occurrences of a string in JavaScript on stackoverflow
I made a workaround by reading the innerHTML from right to left and disregarding the match if there is a "<" character to the left, which means that the match is inside a tag. Although the solution below seems to be manual, yet it works for me for now.
<!DOCTYPE html>
<html>
<input type="text" onkeyup="highlight(this.value)">
<p>Hi! I'm feeling well and happy, hope you too. Thank you.</p>
<p id="WE1"><b>WE</b> wE, We, we.
Only you.
<span id="wemark">mark it in your calendar.</span>
</p>
<script>
function highlight(searchedWords) {
var p = document.getElementsByTagName('p');
for (var i=0; i<p.length; i++) {
p[i].innerHTML = p[i].innerHTML.replace(new RegExp("<mark>", "gi"),(match) => ``);
p[i].innerHTML = p[i].innerHTML.replace(new RegExp("</mark>","gi"),(match) => ``);
}
var words = searchedWords.trim();
while (words.indexOf(" ") > -1) {words = words.replace(" "," ")}
if (!words) return;
words = words.split(" ");
for (var i = 0; i < p.length; i++) {
p[i].innerHTML = mark(p[i].innerHTML, words)
}
}
function mark(str, words) {
try {
for (var j=0; j < words.length; j++) {
var s = str.toLowerCase(),
x = words[j].toLowerCase().trim();
while (s.lastIndexOf(x) > -1) {
var loc = s.lastIndexOf(x), y = loc;
while (y > 0) {
y = y - 1;
if (s.substr(y,1)=="<"||s.substr(y,1)==">") break;
}
if (s.substr(y, 1) != "<") {
str = str.substring(0, loc) + "<mark>"
+ str.substr(loc, x.length) + "</mark>"
+ str.substring(loc + x.length, str.length);
}
s = s.substring(0, loc-1);
}
}
return str;
} catch(e) {alert(e.message)}
}
</script>
</html>

(Javascript) Trying to allow a key press only once in hangman game when it is deemed to be incorrect

Please let me know if there is any additional information I can add to help make my problem more clear!
Im trying to get my hangman game to not allow another key press of the same kind if it is deemed to be incorrect. Once a key press is deemed incorrect it is shown on screen as an incorrect guess and I don't want it to be shown more than once or to count as another incorrect guess as guesses are limited.
Here's a link to my site: https://thy-turk.github.io/Word-Guess-Game/
Here is the code I've been trying to manipulate to allow this.
//if else comparing letter guessed with the current word
if (letterPos.length) {
for(i = 0; i < letterPos.length; i++) {
currentWord[letterPos[i]] = lettersGuessed;
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
} else {
// if (lettersGuessed.includes(letter)) {
// return;
// }
document.getElementById("letters-guessed").innerHTML += lettersGuessed + " ";
guessesLeft--;
document.getElementById("guesses-remain").innerHTML = guessesLeft;
}
The stuff I have commented out is the attempt I kept coming back to, but could never make work.
I know the way I've set this up is less than ideal. I've tried using functions throughout, but just ended up breaking everything.
Here is the entirety of the code for reference.
var currentWord = [];
var answerWord = [];
var lettersReset = "";
var i;
var guessesLeft = 15;
// Array for the word bank of possible answers
var wordAnswers = ["vapor", "wave", "keyboard", "javascript", "coding", "practice", "technology", "hangman", "retro", "internet", "lamborgini", "ferrari", "cellphone", "computer", "headphones", "speakers", "vinyl", "record"];
// Math function to randomly pick a word from the wordbank
var answer = wordAnswers[Math.floor(Math.random() * wordAnswers.length)];
// Variable that counts the number of guesses left
document.getElementById("guesses-remain").innerHTML = guessesLeft;
// Variable that counts the number of wins
var wins = 0;
document.getElementById("num-of-wins").innerHTML = wins;
// Loop that creates empty spaces for the words
for (i = 0; i < answer.length; i++) {
currentWord.push("_");
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
//Function that will evaluate the position of a letter in the word
function wordLetters(letter) {
var letterPos = new Array();
for (i = 0; i < answer.length; i++) {
if (answer[i] === letter)
letterPos.push(i);
}
return letterPos;
}
//Return letters that arent guessed still
function lettersToGuess() {
var i;
var toGuess = 0;
for (i in currentWord) {
if (currentWord[i] === "_")
toGuess++;
}
return toGuess;
}
//Function to capture user input
document.onkeyup = function(event) {
var letter = event.key.toLowerCase();
var lettersGuessed = letter;
var i;
var letterPos = wordLetters(lettersGuessed);
console.log(letter);
//if else comparing letter guessed with the current word
if (letterPos.length) {
for (i = 0; i < letterPos.length; i++) {
currentWord[letterPos[i]] = lettersGuessed;
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
} else {
// if (lettersGuessed.includes(letter)) {
// return;
// }
document.getElementById("letters-guessed").innerHTML += lettersGuessed + " ";
guessesLeft--;
document.getElementById("guesses-remain").innerHTML = guessesLeft;
}
// If user correctly guesses word the game is reset
if (lettersToGuess() == 0) {
guessesLeft = 15;
document.getElementById("guesses-remain").innerHTML = guessesLeft;
document.getElementById("letters-guessed").innerHTML = lettersReset;
answer = wordAnswers[Math.floor(Math.random() * wordAnswers.length)];
currentWord = [];
for (i = 0; i < answer.length; i++) {
currentWord.push("_");
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
wins++;
document.getElementById("num-of-wins").innerHTML = wins;
}
//Resets game if out of guesses
if (guessesLeft === 0) {
guessesLeft = 15;
document.getElementById("guesses-remain").innerHTML = guessesLeft;
document.getElementById("letters-guessed").innerHTML = lettersReset;
answer = wordAnswers[Math.floor(Math.random() * wordAnswers.length)];
currentWord = [];
for (i = 0; i < answer.length; i++) {
currentWord.push("_");
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
}
}
<h1>Press any key to get started!</h1>
<br />
<div class="container">
<p>Wins: </p>
<p><span id="num-of-wins"></span></p><br />
<p>Current Word: </p><br />
<p><span id="active-word"></span></p>
<p>Number of guesses remaining: </p><br />
<p><span id="guesses-remain"></span></p><br />
<p>Letters already Guessed: </p><br />
<p><span id="letters-guessed"></span></p>
</div>
Ok, so I'm gonna put my edited version of your code at the bottom and do the explaining up here.
First, you needed somewhere to keep track of the letters that you had already pressed. I added an array at the top of your script section to keep everything together. This is also important because it is outside the scope of the keyup event
Second, I actually added a little quality of life change in there. You weren't checking if the button pressed was actually a letter so I fixed that by wrapping everything in an if statement and then checking for the letter codes.
Then finally all were doing is using the includes() function. That's gonna check if the letter that was pressed has been seen already. If it has we do nothing. If it hasn't then we'll push that letter into the pastLetters array so that if we see it again we don't punish the user for it. Since the pastLetters array if in the parent scope of this it's persistent and won't be overridden if there's another keydown event.
Also important to note! I added that array to your reset pieces too so that when the game gets reset, the pastLetters array also gets reset.
var currentWord = [];
var answerWord = [];
// Making an array to put the letters that we've already seen into.
var pastLetters = [];
var lettersReset = "";
var i;
var guessesLeft = 15;
// Array for the word bank of possible answers
var wordAnswers = ["vapor", "wave", "keyboard", "javascript", "coding", "practice", "technology", "hangman", "retro", "internet", "lamborgini", "ferrari", "cellphone", "computer", "headphones", "speakers", "vinyl", "record"];
// Math function to randomly pick a word from the wordbank
var answer = wordAnswers[Math.floor(Math.random() * wordAnswers.length)];
// Variable that counts the number of guesses left
document.getElementById("guesses-remain").innerHTML = guessesLeft;
// Variable that counts the number of wins
var wins = 0;
document.getElementById("num-of-wins").innerHTML = wins;
// Loop that creates empty spaces for the words
for (i = 0; i < answer.length; i++) {
currentWord.push("_");
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
//Function that will evaluate the position of a letter in the word
function wordLetters(letter) {
var letterPos = new Array();
for (i = 0; i < answer.length; i++) {
if (answer[i] === letter)
letterPos.push(i);
}
return letterPos;
}
//Return letters that arent guessed still
function lettersToGuess() {
var i;
var toGuess = 0;
for (i in currentWord) {
if (currentWord[i] === "_")
toGuess++;
}
return toGuess;
}
//Function to capture user input
document.onkeyup = function(event) {
// Checking to make sure that the key pressed is actually a letter.
if ((event.keyCode >= 65 && event.keyCode <= 90) || event.keyCode >= 97 && event.keyCode <= 122) {
var letter = event.key.toLowerCase();
var lettersGuessed = letter;
var i;
var letterPos = wordLetters(lettersGuessed);
//if else comparing letter guessed with the current word
if (letterPos.length) {
for (i = 0; i < letterPos.length; i++) {
currentWord[letterPos[i]] = lettersGuessed;
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
} else {
// If the letter has already been seen don't do it again.
if (!pastLetters.includes(letter)) {
// Placing the letter into an array that we can reference outside the scope of the key up event.
pastLetters.push(letter);
document.getElementById("letters-guessed").innerHTML += lettersGuessed + " ";
guessesLeft--;
document.getElementById("guesses-remain").innerHTML = guessesLeft;
}
}
// If user correctly guesses word the game is reset
if (lettersToGuess() == 0) {
guessesLeft = 15;
document.getElementById("guesses-remain").innerHTML = guessesLeft;
document.getElementById("letters-guessed").innerHTML = lettersReset;
answer = wordAnswers[Math.floor(Math.random() * wordAnswers.length)];
currentWord = [];
pastLetters = [];
for (i = 0; i < answer.length; i++) {
currentWord.push("_");
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
wins++;
document.getElementById("num-of-wins").innerHTML = wins;
}
//Resets game if out of guesses
if (guessesLeft === 0) {
guessesLeft = 15;
document.getElementById("guesses-remain").innerHTML = guessesLeft;
document.getElementById("letters-guessed").innerHTML = lettersReset;
answer = wordAnswers[Math.floor(Math.random() * wordAnswers.length)];
currentWord = [];
pastLetters = [];
for (i = 0; i < answer.length; i++) {
currentWord.push("_");
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
}
}
}
<h1>Press any key to get started!</h1>
<br />
<p>Wins: </p>
<p><span id="num-of-wins"></span></p><br />
<p>Current Word: </p><br />
<p><span id="active-word"></span></p>
<p>Number of guesses remaining: </p><br />
<p><span id="guesses-remain"></span></p><br />
<p>Letters already Guessed: </p><br />
<p><span id="letters-guessed"></span></p>

How to manipulate the characters written in a div to work with them afterwards using javascript

function doGetWord(){
var word = F.gword.value;
var wLength = word.length;
for(var i = 0; i < wLength; i++){
document.getElementById("dword").innerHTML += "_ "
}
}
This is a function that will write _ in a div in html, and what I want is to change them if the user types the corresponding input, for example if the first letter is supposed to be "a" then it would change the first _ to "a".
This is what I got so far:
function doGuessWord(){
dummy = F.t.value
if(dummy.length > 1){
dummy = ""
F.t.value = ""
}
for(var x = 0; x < wLength; x++){
if (substr(x, wLength) == dummy ) {
document.getElementById("dword").innerHTML += "_ "
}
else{
document.getElementById("dword").innerHTML += "dummy "
}
}
}
Could you help me out with this one?
Thanks in Advance!!
Something like this?
https://jsfiddle.net/9z66968a/3/
You will have to adapt it a bit. But you should be able to take the parseText function and pass it the params you need to return the text to insert where ever you want
There you go. I believe this is what you wanted. Feel free if you don't understand something
https://jsfiddle.net/vhsf8gpp/2/
var dashArr = [];
var dummyWord = document.getElementById('dummy');
var input = document.querySelector('input');
var counter = 0;
for(let i= 0; i<10;i++)
{
dashArr.push('_');
}
function WriteContent()
{
dummyWord.textContent = dashArr.map(d=>d).join(''); // This gets rid of the ',' inbetween the dashes
}
WriteContent();
//var charArr = [];
document.querySelector('input').addEventListener('keyup',function(){
var inputString = input.value;
dashArr[counter] = inputString.charAt(inputString.length - 1);
WriteContent();
counter++;
})
I used this post for reference.

How to Invert Order of Lines

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

Javascript - String split does not work well

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.

Categories