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

Javascript Split String at First Numeric - Stack Overflow

programmeradmin4浏览0评论

I am trying to split a UK postcode string to only include the initial letters. For example, 'AA1 2BB' would become 'AA.'

I was thinking something like the below.

var postcode = 'AA1 2BB';
var postcodePrefix = postcode.split([0-9])[0];

This does not actually work, but can someone help me out with the syntax?

Thanks for any help.

I am trying to split a UK postcode string to only include the initial letters. For example, 'AA1 2BB' would become 'AA.'

I was thinking something like the below.

var postcode = 'AA1 2BB';
var postcodePrefix = postcode.split([0-9])[0];

This does not actually work, but can someone help me out with the syntax?

Thanks for any help.

Share Improve this question asked Sep 9, 2013 at 19:28 dreamviewerdreamviewer 1551 gold badge2 silver badges8 bronze badges 2
  • 3 postcode.split(/[0-9]/)[0]; maybe? – Matthew Commented Sep 9, 2013 at 19:29
  • Do you want postcodePrefix[1] to contain '1 2BB' or ' 2BB' or does it matter? – user1720624 Commented Sep 9, 2013 at 19:43
Add a comment  | 

4 Answers 4

Reset to default 12

You can try something like this:

var postcode = 'AA1 2BB';
var postcodePrefix =postcode.split(/[0-9]/)[0];

Alternatively, you could use a regex to simply find all alphabetic characters that occur at the beginning of the string:

var postcode = 'AA1 2BB';
var postcodePrefix = postcode.match(/^[a-zA-Z]+/);

If you want any initial characters that are non numeric, you could use:

var postcodePrefix = postcode.match(/^[^0-9]+/);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

"AA1 2BB".split(/[0-9]/)[0];

or

"AA1 2BB".split(/\d/)[0];
var m = postcode.match(/([^\d]*)/);
if (m) {
   var prefix = m[0];
}
发布评论

评论列表(0)

  1. 暂无评论