最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript regex to split numbers and letters - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Nov 17, 2016 at 6:36 Biffen 6,3556 gold badges31 silver badges37 bronze badges asked Nov 17, 2016 at 6:32 MonishaMonisha 1631 gold badge1 silver badge8 bronze badges 2
  • 2 str.match(/[a-zA-Z]+|[0-9]+(?:\.[0-9]+)?|\.[0-9]+/g); – Pranav C Balan Commented Nov 17, 2016 at 6:35
  • thnk you.. it worked – Monisha Commented Nov 17, 2016 at 7:02
Add a comment  | 

2 Answers 2

Reset to default 31

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.

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

发布评论

评论列表(0)

  1. 暂无评论