I am creating a function to calculate the division of 2 numbers that are inside an array. The problem I have is that the division is done the other way around. ej: if I put 10/2 as parameters, the result that returns is 2/10. So how could I solve this error?
Here I leave the complete code, just check the code of the function "fDividir".
Code javascript:
sysc es un sistema que podrás usar para implementar para la creación de tu calculadora.
// inicio de las funciones
//función sumar
const fSumar = function (valores = "0"){
let arregloNum = valores.split("+");
let oSuma = 0;
for (let i = 0; i < arregloNum.length; i++){
oSuma = parseInt(arregloNum[i]) + oSuma;
}
return oSuma;
}
//función restar
const fRestar = function (valores = "0"){
let arregloNum = valores.split("-");
let oResta = 0;
for (let i = 0; i < arregloNum.length; i++){
oResta = parseInt(arregloNum[i]) - oResta;
}
return oResta;
}
// función multiplicar
const fMultiplicar = function (valores = "0"){
let arregloNum = valores.split("×");
let oMultiplicacion = 1;
for (let i = 0; i < arregloNum.length; i++){
oMultiplicacion = parseInt(arregloNum[i]) * oMultiplicacion;
}
return oMultiplicacion;
}
// función dividir
const fDividir = function (valores = "0"){
let arregloNum = valores.split("/");
let oDivision = 1;
for (let i = 0; i < arregloNum.length; i++){
oDivision = parseInt(arregloNum[i]) / oDivision;
}
return oDivision;
}
// fin de las funciones
console.log(fDividir("10/2")); // 0.2
Change your division function:
// función dividir
const fDividir = function (valores = "0"){
let arregloNum = valores.split("/");
let oDivision = 1;
for (let i = arregloNum.length - 1; i > 0; i--){
oDivision = parseInt(arregloNum[i]) * oDivision;
}
return arregloNum[0] / oDivision;
}
Note that you were inverting the divisors order...
Another, possible solution:
// función dividir
const fDividir = function (valores = "0"){
let arregloNum = valores.split("/");
let oDivision = arregloNum[0];
for (let i = 1; i < arregloNum.length; i++){
oDivision /= parseInt(arregloNum[i]);
}
return oDivision;
}
I am getting the this message "Uncaught TypeError: Cannot read property 'split' of null" for this linesplitted = elements[i].nextSibling.nodeValue.split("||"); The code is in below. I will appreciate your input to solve this. The code has worked before. I think it is something about new php oder jquery...
$('#r_NEStd').hide(); // Das Feld ist am Anfang versteckt und duch klicken
auf NE wird wieder gezeigt.
$("input[name='x_Posten[]'], input[name='x_NE[]']").click(function() { //
Field2 has multiple inputs(checkboxes) so they should be selected by name
document.getElementById("x_Total").readOnly = true;
document.getElementById("x_Auslagen").readOnly = true;
document.getElementById("x_RBetrag").readOnly = true;
if ($("input[name='x_Posten[]']:checked").val() &&
$("input[name='x_NE[]']:checked").val()) { // WENN NichtErhaeltlichkeit und
Posten geklickt sind
document.finvoicesadd.x_Total.value = '';
var Anzahl = 0;
var Auslagen = 0;
var AuslagenMwSt = 0;
var Total = 0;
var splitted;
var nestdsatz = document.finvoicesadd.x_NEStd.value;
var e = document.getElementById("x_Vorschuss");
var VorschussValue = e.options[e.selectedIndex].value;
var nestdsatz = document.finvoicesadd.x_NEStd.value;
var elements = document.getElementsByName("x_Posten[]");
for (i = 0; i < elements.length; i++) {
if (elements[i].checked) {
splitted = elements[i].nextSibling.nodeValue.split("||");
Auslagen = Auslagen + +parseFloat(splitted[4]);
AuslagenMwSt = AuslagenMwSt + +(parseFloat(splitted[4]) *
(1 + parseFloat(splitted[5])));
Anzahl = Anzahl + +parseFloat(splitted[2]);
Total = Total + +(parseFloat(splitted[2] * nestdsatz) *
(1 + parseFloat(splitted[5])));
}
}
document.finvoicesadd.x_Auslagen.value = Auslagen.toFixed(2);
document.finvoicesadd.x_Total.value = (Total + AuslagenMwSt).toFixed(2);
document.finvoicesadd.x_RBetrag.value = (Math.round(((Total +
AuslagenMwSt) - VorschussValue) * 20, 0) / 20).toFixed(2);
document.finvoicesadd.x_Vorlage.value = "rechnungne";
} else { // WENN x_Posten oder NE nicht oder nur ein Feld gelickt ist
document.finvoicesadd.x_Total.value = '';
var Anzahl = 0;
var Auslagen = 0;
var Total = 0;
var splitted;
var e = document.getElementById("x_Vorschuss");
var VorschussValue = e.options[e.selectedIndex].value;
var nestdsatz = document.finvoicesadd.x_NEStd.value;
var elements = document.getElementsByName("x_Posten[]");
for (i = 0; i < elements.length; i++) {
if (elements[i].checked) {
splitted = elements[i].nextSibling.nodeValue.split("||");
// Auslagen = Auslagen+ +(parseFloat(splitted[4])*
(1 + parseFloat(splitted[5])));
Auslagen = Auslagen + +parseFloat(splitted[4]);
Anzahl = Anzahl + +parseFloat(splitted[3]);
Total = Total + +parseFloat(splitted[6]);
}
}
document.finvoicesadd.x_Auslagen.value = Auslagen.toFixed(2);
document.finvoicesadd.x_Total.value = (Total).toFixed(2);
document.finvoicesadd.x_RBetrag.value = (Math.round(((Total) -
VorschussValue) * 20, 0) / 20).toFixed(2);
document.finvoicesadd.x_Vorlage.value = "rechnung";
}
});
Replace this:
if (elements[i].checked) {
with this:
debugger;
if (elements[i].checked && elements[i].nextSibling.nodeValue != null) {
This will solve the error, although I have no idea which repercussions it will have on your program.
The error is given by the fact that elements[i].nextSibling.nodeValue is null when you're checking it.
I created an easy game with Javascript, the purpose is to pick a square who has a RGB color(random generated) from a list of squares and show the length of time until the square with the correct color is found. Everything works fine, except after the time is shown corectly and I click on a button, the time continues to change and show again a new time and i don't want that. I try to give display: none or textcontent ="" after showing the time, but is not working.
The problem is in these lines:
end = new Date().getTime();
timeTaken = (end - start) / 1000;
timp.style.display ="inline";
timp.innerHTML = "Timpul tau: " + timeTaken + " s.";
Thanks!
The game link: https://ionutbedeoan.github.io/joc/
My javascript code :
var numSquares = 6;
var colors = generateRandomColors(numSquares);
var squares = document.querySelectorAll(".square");
var pickedColor = pickColor();
var colorDisplay = document.getElementById("colorDisplay");
var messageDisplay = document.querySelector("#message");
var h1 = document.querySelector("h1");
var resetButton = document.querySelector("#reset");
var easyBtn = document.querySelector("#easyBtn");
var hardBtn = document.querySelector("#hardBtn");
var numSquares = 6;
var timp = document.getElementById("timeTaken");
var start = new Date().getTime();
var end;
var timeTaken;
easyBtn.addEventListener("click", function () {
start = new Date().getTime();
numSquares = 3;
this.classList.add("selected");
hardBtn.classList.remove("selected");
colors = generateRandomColors(numSquares);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
for (var i = 0; i < 3; i++) {
squares[i].style.backgroundColor = colors[i];
}
for (var i = 3; i < squares.length; i++) {
squares[i].style.display = "none";
}
timp.textContent= "";
messageDisplay.textContent = "";
h1.style.background = "steelblue";
});
hardBtn.addEventListener("click", function () {
start = new Date().getTime();
this.classList.add("selected");
numSquares = 6;
easyBtn.classList.remove("selected");
colors = generateRandomColors(numSquares);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
for (var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = colors[i];
squares[i].style.display = "block";
}
messageDisplay.textContent = "";
timp.textContent= "";
h1.style.background = "steelblue";
});
resetButton.addEventListener("click", function () {
start = new Date().getTime();
//generare noi culori
colors = generateRandomColors(numSquares);
//alegem o noua culoare random din vector
pickedColor = pickColor();
//schimbam colorDisplay sa fie la fel cu culoarea aleasa
colorDisplay.textContent = pickedColor;
//schimbare culori ale patratelor
for (var i = 0; i < squares.length; i++) {
// adaug culorile la fiecare patrat
squares[i].style.background = colors[i];
}
h1.style.background = "steelblue";
messageDisplay.textContent = "";
this.textContent = "Culori noi";
timp.textContent= "";
});
colorDisplay.textContent = pickedColor;
for (var i = 0; i < squares.length; i++) {
// adaug culorile la fiecare patrat
squares[i].style.background = colors[i];
//cand dau click pe un patrat
squares[i].addEventListener("click", function () {
// pun intr-o variabila culoarea patratatului ca sa o verific cu culoarea pe care trebuie sa o ghicesc, pentru a vedea daca am nimerit culoarea
var clickedColor = this.style.backgroundColor;
if (clickedColor === pickedColor) {
messageDisplay.textContent = "Corect!"
resetButton.textContent = "Joc nou"
changeColors(clickedColor);
h1.style.backgroundColor = clickedColor;
end = new Date().getTime();
timeTaken = (end - start) / 1000;
timp.style.display ="inline";
timp.innerHTML = "Timpul tau: " + timeTaken + " s.";
} else {
this.style.backgroundColor = "#232323";
messageDisplay.textContent = "Gresit!";
}
});
};
function changeColors(color) {
//schimbam culoarea la fiecare patrat
for (var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = color;
}
}
function pickColor() {
var random = Math.floor(Math.random() * colors.length);
return colors[random];
}
function generateRandomColors(num) {
// fac un vector
var arr = [];
//adaugam numarul de culori random
for (var i = 0; i < num; i++) {
//alegem o culoare random si o bagam in vector
arr[i] = randomColor();
}
//returnam vectorul
return arr;
}
function randomColor() {
// alegem un rosu intre 0 si 255
var r = Math.floor(Math.random() * 256);
//alegem un verde intre 0 si 255
var g = Math.floor(Math.random() * 256);
//alegem un albastru intre 0 si 255
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + ", " + g + ", " + b + ")";
}
Thanks !
Check if the correct answer was already selected in your square's event listener and return if so. This will prevent it from running the rest of the event listener's code where it updates the time.
if (clickedColor === pickedColor) {
if (messageDisplay.textContent === "Corect!") return;
...
} else {
...
}
I've seen a few Bitcoin Address form validation scripts for various languages, but surprisingly can't really find anything for two common web languages, Javascript and PHP.
Here's one for Python, but is there one for PHP and/or JS?
from hashlib import sha256
digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def decode_base58(bc, length):
n = 0
for char in bc:
n = n * 58 + digits58.index(char)
return n.to_bytes(length, 'big')
def check_bc(bc):
bcbytes = decode_base58(bc, 25)
return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]
if __name__ == '__main__':
bc = '1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i'
assert check_bc(bc)
assert not check_bc( bc.replace('N', 'P', 1) )
assert check_bc('1111111111111111111114oLvT2')
assert check_bc("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j")
Here's a JSFiddle: http://jsfiddle.net/timrpeterson/XsCQq/2/
And here's the full code upon which the JSFiddle is based:
<html>
<head>
<script type="text/javascript" src="http://dl.dropboxusercontent.com/u/28441300/BigInt.js"></script>
<script type="text/javascript" src="http://dl.dropboxusercontent.com/u/28441300/sha256.js"></script>
</head>
<body>
<div id="text">
</div>
<script type="text/javascript">
var address = "1Eym7pyJcaambv8FG4ZoU8A4xsiL9us2zz";
if (check(address)) {
document.getElementById('text').innerHTML += "valid";
} else {
document.getElementById('text').innerHTML += "invalid";
}
function check(address) {
var decoded = base58_decode(address);
if (decoded.length != 25) return false;
var cksum = decoded.substr(decoded.length - 4);
var rest = decoded.substr(0, decoded.length - 4);
var good_cksum = hex2a(sha256_digest(hex2a(sha256_digest(rest)))).substr(0, 4);
if (cksum != good_cksum) return false;
return true;
}
function base58_decode(string) {
var table = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
var table_rev = new Array();
var i;
for (i = 0; i < 58; i++) {
table_rev[table[i]] = int2bigInt(i, 8, 0);
}
var l = string.length;
var long_value = int2bigInt(0, 1, 0);
var num_58 = int2bigInt(58, 8, 0);
var c;
for(i = 0; i < l; i++) {
c = string[l - i - 1];
long_value = add(long_value, mult(table_rev[c], pow(num_58, i)));
}
var hex = bigInt2str(long_value, 16);
var str = hex2a(hex);
var nPad;
for (nPad = 0; string[nPad] == table[0]; nPad++);
var output = str;
if (nPad > 0) output = repeat("\0", nPad) + str;
return output;
}
function hex2a(hex) {
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
function a2hex(str) {
var aHex = "0123456789abcdef";
var l = str.length;
var nBuf;
var strBuf;
var strOut = "";
for (var i = 0; i < l; i++) {
nBuf = str.charCodeAt(i);
strBuf = aHex[Math.floor(nBuf/16)];
strBuf += aHex[nBuf % 16];
strOut += strBuf;
}
return strOut;
}
function pow(big, exp) {
if (exp == 0) return int2bigInt(1, 1, 0);
var i;
var newbig = big;
for (i = 1; i < exp; i++) {
newbig = mult(newbig, big);
}
return newbig;
}
function repeat(s, n){
var a = [];
while(a.length < n){
a.push(s);
}
return a.join('');
}
</script>
</body>
</html>
And here is a PHP example (assuming your have PHP BC-Math):
<?php
function checkAddress($address)
{
$origbase58 = $address;
$dec = "0";
for ($i = 0; $i < strlen($address); $i++)
{
$dec = bcadd(bcmul($dec,"58",0),strpos("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",substr($address,$i,1)),0);
}
$address = "";
while (bccomp($dec,0) == 1)
{
$dv = bcdiv($dec,"16",0);
$rem = (integer)bcmod($dec,"16");
$dec = $dv;
$address = $address.substr("0123456789ABCDEF",$rem,1);
}
$address = strrev($address);
for ($i = 0; $i < strlen($origbase58) && substr($origbase58,$i,1) == "1"; $i++)
{
$address = "00".$address;
}
if (strlen($address)%2 != 0)
{
$address = "0".$address;
}
if (strlen($address) != 50)
{
return false;
}
if (hexdec(substr($address,0,2)) > 0)
{
return false;
}
return substr(strtoupper(hash("sha256",hash("sha256",pack("H*",substr($address,0,strlen($address)-8)),true))),0,8) == substr($address,strlen($address)-8);
}
?>
Here is a better version of #Tim-Peterson 's answer. It fixes the base58 implementation he was using (which would not validate the address "12EJmB3cMGRNveskzA7g7kxW32gSbo2dHF".
I combined the validation code with all the needed libraries and removed a lot that wasn't needed. It only exposes a single api: "checkAddress". I created a little home-page for it, where you can download the module source or the minified version: http://www.julianhaight.com/javascript.shtml
The corrected base58_decode (from https://github.com/cryptocoinjs/bs58):
// from https://github.com/cryptocoinjs/bs58
// Base58 encoding/decoding
// Originally written by Mike Hearn for BitcoinJ
// Copyright (c) 2011 Google Inc
// Ported to JavaScript by Stefan Thomas
// Merged Buffer refactorings from base58-native by Stephen Pair
// Copyright (c) 2013 BitPay Inc
var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
var ALPHABET_MAP = {}
for(var i = 0; i < ALPHABET.length; i++) {
ALPHABET_MAP[ALPHABET.charAt(i)] = i
}
var BASE = 58
function base58_decode(string) {
if (string.length === 0) return []
var i, j, bytes = [0]
for (i = 0; i < string.length; i++) {
var c = string[i]
if (!(c in ALPHABET_MAP)) throw new Error('Non-base58 character')
for (j = 0; j < bytes.length; j++) bytes[j] *= BASE
bytes[0] += ALPHABET_MAP[c]
var carry = 0
for (j = 0; j < bytes.length; ++j) {
bytes[j] += carry
carry = bytes[j] >> 8
bytes[j] &= 0xff
}
while (carry) {
bytes.push(carry & 0xff)
carry >>= 8
}
}
// deal with leading zeros
for (i = 0; string[i] === '1' && i < string.length - 1; i++) bytes.push(0)
bytes = bytes.reverse()
output = '';
for (i=0; i<bytes.length; i++) {
output += String.fromCharCode(bytes[i]);
}
return output;
}
Bitcoin Address (example: 3QJmV3qfvL9SuYo34YihAf3sRCW3qSinyC) is not valid in many the PHP examples. One of the example which works fine especially to the above address is:
Click here to see the PHP Function to validate Bitcoin Address
I wrote a simple PHP library to do this based on the answers above. It can be found at my related github repo:
<?php
class Btc_address_validator {
/**
* [validate description]
* #param String $address BTC Address string
* #return Boolean validation result
*/
public function validate($address)
{
$addr = $this->decode_base58($address);
if (strlen($addr) != 50)
{
return false;
}
$check = substr($addr, 0, strlen($addr) - 8);
$check = pack("H*", $check);
$check = strtoupper(hash("sha256", hash("sha256", $check, true)));
$check = substr($check, 0, 8);
return $check == substr($addr, strlen($addr) - 8);
}
private function encode_hex($dec)
{
$hexchars = "0123456789ABCDEF";
$return = "";
while (bccomp($dec, 0) == 1)
{
$dv = (string) bcdiv($dec, "16", 0);
$rem = (integer) bcmod($dec, "16");
$dec = $dv;
$return = $return . $hexchars[$rem];
}
return strrev($return);
}
/**
* Convert a Base58-encoded integer into the equivalent hex string representation
*
* #param string $base58
* #return string
* #access private
*/
private function decode_base58($base58)
{
$origbase58 = $base58;
$base58chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
$return = "0";
for ($i = 0; $i < strlen($base58); $i++)
{
$current = (string) strpos($base58chars, $base58[$i]);
$return = (string) bcmul($return, "58", 0);
$return = (string) bcadd($return, $current, 0);
}
$return = $this->encode_hex($return);
//leading zeros
for ($i = 0; $i < strlen($origbase58) && $origbase58[$i] == "1"; $i++)
{
$return = "00" . $return;
}
if (strlen($return) % 2 != 0)
{
$return = "0" . $return;
}
return $return;
}
}
For those using javascript, you can use wallet-address-validator javascript plugin.
<script src="wallet-address-validator.min.js"></script>
// WAValidator is stored in the windows object
networkType - Optional. Use 'prod' (default) to enforce standard address, 'testnet' to enforce testnet address and 'both' to enforce nothing.
var valid = WAValidator.validate('12h7E1q5UUoPgZ1VtcYb57maFF9Cbk4u5X','BTC','both');
if(valid){
alert('This is a valid address');
} else {
alert('Address INVALID');
}
// will alert "This is a valid address"
var valid = WAValidator.validate('12h7E1q5UUoPgZ1VtcYb57maFF9Cbk4u5X', 'ETH', 'both');
if(valid){
alert('This is a valid address');
} else {
alert('Address INVALID');
}
// will alert "Address INVALID"
Here is a short and modern implementation in Javascript which depends on CryptoJS:
import sha256 from 'crypto-js/sha256'
import CryptoJS from 'crypto-js'
function isBTCAddress (address) {
if (!/^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(address)) return false
const bufferLength = 25
let buffer = new Uint8Array(bufferLength)
const digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
for (var i = 0; i < address.length; i++) {
const num = digits58.indexOf(address[i])
// buffer = buffer * 58 + num
let carry = 0
for (var j = bufferLength - 1; j >= 0; --j) {
// num < 256, so we just add it to last
const result = buffer[j] * 58 + carry + (j === bufferLength - 1 ? num : 0)
buffer[j] = result % (1 << 8)
carry = Math.floor(result / (1 << 8))
}
}
// check whether sha256(sha256(buffer[:-4]))[:4] === buffer[-4:]
const hashedWords1 = sha256(CryptoJS.lib.WordArray.create(buffer.slice(0, 21)))
const hashedWords = sha256(hashedWords1).words
// get buffer[-4:] with big-endian
const lastWordAddress = new DataView(buffer.slice(-4).buffer).getInt32(0, false)
const expectedLastWord = hashedWords[0]
return lastWordAddress === expectedLastWord
}
This is a nice REGEX from this answer that I have made into a function for you. Only works with non-segwit addresses.
function validate_bitcoin_address(btc_address)
{
return btc_address.match("^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$") !== null;
}
alert(validate_bitcoin_address("16CbQcqDtBak5NzPbmFP1v9Pi4DwP5G4Wn")); //example usage
The regex matches strings that:
Starts with 1 or 3
Afterwards, 25 to 34 characters of either a-z, A-Z, or 0-9 but not l, I, O and 0
The REGEX excludes characters that are not allow in bitcoin addresses (l, I, O and 0)
This works for each address format (today) https://github.com/Merkeleon/php-cryptocurrency-address-validation.
It needs BC Math, so probably... sudo apt install php-bcmath
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.