Shred string into random parts

2

I need a JS script that breaks any string into random parts, say I have a string:

x = "Deliciosogostoeobomgostodasnuvensseremfeitasdealgodao"

and after it has been inserted into the script, it can be returned like this:

"Del icios ogos t oeobo mgosto das nuvensser emf eitasde a lgod ao"
    
asked by anonymous 19.02.2018 / 03:15

2 answers

2

You can do this by breaking the string into parts of a maximum of 9 characters (this you can change in the code where you have 9 ) and adding to an array and then joining everything with join :

Example:

var x = "Deliciosogostoeobomgostodasnuvensseremfeitasdealgodao",
    x_novo = [];
while(x.length > 0){
   var rn1 = Math.floor(Math.random()*9)+1,
       parte = x.substring( x.charAt(0), rn1 );
   x_novo.push(parte);
   x = x.replace(parte,'');
}

x_novo = x_novo.join(" ");
console.log(x_novo);

Example without using array:

var x = "Deliciosogostoeobomgostodasnuvensseremfeitasdealgodao",
    x_novo = '';
while(x.length > 0){
   var rn1 = Math.floor(Math.random()*9)+1,
   parte = x.substring(x.charAt(0), rn1);
   x_novo += (x_novo.length > 0 ? ' ' : '')+parte;
   x = x.replace(parte, '');
}

console.log(x_novo);
    
19.02.2018 / 05:00
3

I created a function that does this work, however, I advise you to test and optimize it before applying it to a real case, especially when the string is too large. I would do this on the server-side and send the processed string to the client-side.

See:

function dividirStrPor(str, caractereDivisao, pedacos)
{
  var tam = str.length;

  for (var i = 0; i < pedacos; i++)
  {
    posicao = Math.floor(Math.random() * (tam - 0 + 1) + 0);

    str = str.slice(0, posicao) + caractereDivisao + str.slice(posicao);
  }

  return str;
}


var str = "Deliciosogostoeobomgostodasnuvensseremfeitasdealgodao";

var resultado = dividirStrPor(str, " ", 12);

console.log(resultado);

Output:

  

The output changes each call of the function, due to the random position in which the division character is inserted into the string.

See working at repl.it .

Sources:

JavaScript: How can I insert a string at a specific index
Generate random number between two numbers in JavaScript

    
19.02.2018 / 03:46