Skip to content Skip to sidebar Skip to footer

Javascript: Split String By Characters Only Or By Characters + Number If Present

How can I split JavaScript string by characters OR by characters+numbers if present? Example: Just characters: var items = 'asdaasf'; //I am using items.split(''); so that's okay.

Solution 1:

Split on every position where the following character is a letter. This can be done with a lookahead:

> "a2sd12a3".split(/(?=[a-z])/i)
["a2", "s", "d12", "a3"]

Solution 2:

If you would just like to split it by character or character followed by number

var reg =  /([a-z]\d*)/g;
var myString = 'something'
myString.match(reg)

@Felix Kling answer is more elegant with the lookahead , but if you want to stick to simplest possible, assuming it always starts with a character.

Solution 3:

Similar approach to Abraham Adam's, but updated to include case-insensitivity, by using the following regex: /[a-z]\d*/ig

var regexVal = /[a-z]\d*/ig;

var test1 = "asdaasf";
var test2 = "a2sdaa5sf";
var test3 = "a2sd12a3";
var test4 = "a1b2c3de45f6gh78i9j0";
var test5 = "a1b2c3De45f6gH78I9j0";

console.log(test1.match(regexVal));  // ["a", "s", "d", "a", "a", "s", "f"]
console.log(test2.match(regexVal));  // ["a2", "s", "d", "a", "a5", "s", "f"]
console.log(test3.match(regexVal));  // ["a2", "s", "d12", "a3"]
console.log(test4.match(regexVal));  // ["a1", "b2", "c3", "d", "e45", "f6", "g", "h78", "i9", "j0"]
console.log(test5.match(regexVal));  // ["a1", "b2", "c3", "D", "e45", "f6", "g", "H78", "I9", "j0"]

Solution 4:

To complement @FelixKling's answer, without relying exclusively on a regex, you can reproduce the logic fairly easily:

var input = "a1b2c3de45f6gh78i9j0";

var chunks = [];
var accum = "";
var lastWasDigit = false;
var isDigitRex = /[0-9]/;

Array.from(input).forEach(function (i) {
  var isDigit = isDigitRex.exec(i);
  if (lastWasDigit && !isDigit) {
    chunks.push(accum);
    accum = "" + i;
  } else {
    accum += i;
  }
  lastWasDigit = isDigit;
})

console.log(chunks);

Post a Comment for "Javascript: Split String By Characters Only Or By Characters + Number If Present"