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.
谢谢你的帮助。
4 个解决方案
#1
6
You can try something like this:
你可以尝试这样的事情:
var postcode = 'AA1 2BB';
var postcodePrefix =postcode.split(/[0-9]/)[0];
#2
3
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]+/);
#3
0
var m = postcode.match(/([^\d]*)/);
if (m) {
var prefix = m[0];
}
#4
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];
#1
6
You can try something like this:
你可以尝试这样的事情:
var postcode = 'AA1 2BB';
var postcodePrefix =postcode.split(/[0-9]/)[0];
#2
3
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]+/);
#3
0
var m = postcode.match(/([^\d]*)/);
if (m) {
var prefix = m[0];
}
#4
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];