Javascript Split String on first digital

I am trying to split a UK zip code string to include only the initial letters. For example, “AA1 2BB” will become “AA.”

I was thinking of something like below.

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

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

Thanks for any help.

+6
source share
4 answers

You can try something like this:

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

Alternatively, you can use regex to simply find all the alphabetic characters that appear at the beginning of the line:

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

If you want the leading characters to be non-numeric, you can use:

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

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


All Articles