JavaScript regex to separate numbers and letters

I need a regex pattern to split a string into numbers and letters. That is, .1abc2.5efg3mnoit should be divided by [".1","abc","2.5","efg","3","mno"].

My current regex is:

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

The result obtained:

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

The number is .1taken for 1, while I need it as .1.

+7
source share
2 answers

If we are talking about separating letters from non-letters, then the regular expression can be made quite simple:

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

those. correspond to a group of letters or a group of non-letters.

+15
source

var z = ".1abc2.5efg3mno".match(/[\d\.]+|\D+/g);
console.log(z);
Run codeHide result
0
source

Source: https://habr.com/ru/post/1661021/


All Articles