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

Asked

Viewed 3,898 times

4

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

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

Thank you in advance.

3 answers

4


A solution making use of the method match() 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"]

  • 2

    This expression has errors, for example the string 123456789123 would return ["12345678", "12", "3"], however, the expression /.{1,8}/g will return the desired result.

  • @Oeslei Thanks for the alert, I was doing tests and editing, already simplified and corrected.

  • 1

    Thank you very much the expression /.{1,8}/g worked perfectly! Thanks XD

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);

  • Thank you @old7 this is undoubtedly an option when regular repression for some reason is not allowed, thanks

0

I’ll leave as a contribution port of function str_split() PHP for Javascript by the 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 indices being the first composed by substring 12345678 and the second by substring 98.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.