简体   繁体   English

Javascript在第一个数字处拆分字符串

[英]Javascript Split String at First Numeric

I am trying to split a UK postcode string to only include the initial letters. 我试图将英国邮政编码字符串拆分为仅包含首字母。 For example, 'AA1 2BB' would become 'AA.' 例如,'AA1 2BB'将变为'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. 谢谢你的帮助。

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]+/);
var m = postcode.match(/([^\d]*)/);
if (m) {
   var prefix = m[0];
}
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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM