How to 'break' a text at each character range - Javascript

4

I would like to know how to 'break' (split function) one text every 8 characters in javascript for example:

var teste = '1234567898'
teste.split({a cada 8 caracteres})
//retorna ['12345678', '898'];

Thank you in advance.

    
asked by anonymous 18.12.2014 / 19:57

3 answers

4

A solution using the match() method. with a regular expression:

var teste = '1234567898';

alert(teste.match(/.{1,8}/g));        // Devolve: 12345678,98
console.log(teste.match(/.{1,8}/g));  // Devolve: ["12345678", "98"]
    
18.12.2014 / 20:08
3

var texto = "x2345678y2345678z23";
var dist = 8;
var resultado = new Array(parseInt(texto.length / dist));
for (var x = 0; x < texto.length / dist; x++) {
    resultado[x] = texto.substring(0 + x * dist, (x + 1) * dist);
}
document.write(resultado);
    
18.12.2014 / 20:22
0

I'll make the port of the PHP str_split () function for JavaScript made by the staff of PHPJS.org

function str_split(string, split_length) {
  //  discuss at: http://phpjs.org/functions/str_split/
  // original by: Martijn Wieringa
  // improved by: Brett Zamir (http://brett-zamir.me)
  // bugfixed by: Onno Marsman
  //  revised by: Theriault
  //  revised by: Rafał Kukawski (http://blog.kukawski.pl/)
  //    input by: Bjorn Roesbeke (http://www.bjornroesbeke.be/)
  //   example 1: str_split('Hello Friend', 3);
  //   returns 1: ['Hel', 'lo ', 'Fri', 'end']

  if (split_length === null) {
    split_length = 1;
  }
  if (string === null || split_length < 1) {
    return false;
  }
  string += '';
  var chunks = [],
    pos = 0,
    len = string.length;
  while (pos < len) {
    chunks.push(string.slice(pos, pos += split_length));
  }

  return chunks;
}

console.log( str_split( '1234567898', 8 ) );

The result is the same: An array of two indexes being the first composed by substring 12345678 and the second by substring 98.     

20.12.2014 / 21:43