29358

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.

Now if I have numbers:

var items = "a2sdaa5sf";

I want it to split into array so I have result like:

[a2,s,d,a,a5,s,f]

So that it counts as 1 character if letter is followed by a number.

Would I use regex? What would syntax be? I am not too familiar with RegEx.

Answer1:

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

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

Answer2:

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.

Answer3:

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"]

Answer4:

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

Recommend

  • Error in formula field of crystal reports when no records found
  • Get sum of a field per page in crystal report
  • What VST/VLD actually do?
  • Crystal Reports formula field: IF ISNULL(decimal) THEN 0.00 … does not work correctly
  • Struggling to combine two Greps statements
  • Copy rows of dataframes in R
  • validate url without www. or http://
  • Correct ISO week numbering in Crystal Reports XI
  • JavaScript: Split string by characters only or by characters + number if present
  • Extend a regular expression to negative number
  • rbind 2 vectors of different lengths by their names
  • PHP replace preceding substrings of some other substring
  • Two very close regexes with lookahead assertions in Python - why does re.split() behave differently?
  • Iterating through JSON using System.Json
  • Excel: how to create a number in a column according to a text value in other column?
  • Ruby regex: extract a list of urls from a string
  • regexp incorreclty split: by commas but not within brackets (both ) and ] )
  • Is it possible to refresh a div on a radio button click?
  • Retrieve List of Cells in Excel Where Column Equals Something
  • Batch file: run command in a cmd.exe launched as a different user using batch file
  • How do I add “&Source” to DataNavigateUrlFormatString?
  • Fortran: Array of arbitrary dimension?
  • How to run a query between dates and times?
  • How to use regex negative lookahead
  • Simple regex for domain names
  • Usage of local dart library
  • Python: Split a String Field into 3 Separate Fields using Lambda
  • how can I compare dates in array to find the earliest one?
  • Divide a $1 by 3 and adjusting 1 cent
  • How do I shift the decimal place in Python?
  • SAXReader not re-ecape characters
  • GridView breaks while scrolling
  • Blackberry - Custom EditField Cursor
  • preg_replace Double Spaces to tab (\\t) at the beginning of a line
  • Extracting HTML between tags
  • MongoDB in PHP using aggregate to group by _id is null not working
  • Body moving without any force applied? (Box2d)
  • Why HTML5 Canvas with a larger size stretch a drawn line?
  • python regex in pyparsing
  • Android Google Maps API OnLocationChanged only called once