PHP function str_split in Javascript


PHP function str_split in Javascript (method of locutus.io)

/* Source: locutus.io */
function str_split(string, splitLength) {
  if (splitLength === null) {
    splitLength = 1
  }
  if (string === null || splitLength < 1) {
    return false
  }
  string += ''
  var chunks = []
  var pos = 0
  var len = string.length
  while (pos < len) {
    chunks.push(string.slice(pos, pos += splitLength))
  }
  return chunks
}

Method of locutus.io can work with ASCII string, but with non-ASCII string (like UTF8 string), this doesn’t work successfully!

Example:

console.log(str_split("\uD83D\uDCAB\u{2122}",1))

Result:

["�", "�", "™"]

But result in PHP:

print_r(str_split(html_entity_decode("&#xD83D;&#xDCAB;&#x2122;", 0, 'UTF-8')))
Array
(
    [0] => í
    [1] =>  
    [2] => ½
    [3] => í
    [4] => ²
    [5] => «
    [6] => â
    [7] => „
    [8] => ¢
)

We can use the method in this artice: Javascript: read ASCII characters from Unicode string, now we write own method:

function str_split(string, splitLength) {
  if (splitLength == undefined) {
    splitLength = 1
  }
  if (string === null || splitLength < 1) {
    return false
  }
  string += ''
  var asciis = stringtoasciis(string);
  //console.log(asciis)
  var chunks = []
  var pos = 0
  var len = asciis.length;
  while (pos < len) {
    chunks.push(asciis.slice(pos, pos += splitLength))
  }
  return chunks.map(function(a) {
    return a.map(function(c) {
      return String.fromCharCode(c)
    }).join("")
  });
}

Try it yourself

1 Comment

Leave a Reply