Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Split String at First Numeric

Tags:

javascript

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.

like image 890
dreamviewer Avatar asked Sep 09 '13 19:09

dreamviewer


People also ask

How to split string with in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you split the first character of a string in Python?

Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) . The split() method only performs a single split when the maxsplit argument is set to 1 .


1 Answers

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]+/);
like image 156
Asad Saeeduddin Avatar answered Sep 22 '22 23:09

Asad Saeeduddin