Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript regex to split numbers and letters

I need regex pattern to split a string into numbers and letters. I.e. .1abc2.5efg3mno should be split into [".1","abc","2.5","efg","3","mno"].

The current regex I tried is:

var str = ".1abc2.5efg3mno";
regexStr= str.match(/[a-zA-Z]+|[0-9]+(?:\.[0-9]+|)/g);

Output obtained is:

["1","abc","2.5","efg","3","mno"]

The number .1 is taken as 1 whereas I need it as .1.

like image 315
Monisha Avatar asked Nov 17 '16 06:11

Monisha


People also ask

How to split using regex in JavaScript?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.


1 Answers

If it's a matter of separating letters from non-letters, then the regex can be made quite simple:

var str = ".1abc2.5efg3mno";
var regexStr = str.match(/[a-z]+|[^a-z]+/gi);
console.log(regexStr);

I.e. match a group of letters or a group of non-letters.

like image 169
Biffen Avatar answered Sep 16 '22 13:09

Biffen