5

I have a string which represents an address in Javascript, say, "Some address, city, postcode".

I am trying to get the 'postcode' part out.

I want to use the split method for this. I just want to know a regex expression that will find the last occurrence of ' , ' in my string.

I have tried writing expressions such as

address.split("/\,(?=[^,]*$)/"); 

and

address.split(",(?=[^,]*$)");

But these don't seem to work. Help!

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Hamza Tahir
  • 416
  • 5
  • 13

4 Answers4

9

If you want to use .split() just split on "," and take the last element of the resulting array:

var postcode = address.split(",").pop();

If you want to use regex, why not write a regex that directly retrieves the text after the last comma:

var postcode = address.match(/,\s*([^,]+)$/)[1]

The regex I've specified matches:

,          // a comma, then
\s*        // zero or more spaces, then
([^,]+)    // one or more non-comma characters at the
$          // end of the string

Where the parentheses capture the part you care about.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
5

pop() will remove the last element of an array:

address.split(",").pop()  

you can use this

PSR
  • 39,804
  • 41
  • 111
  • 151
  • Thats a good way of going about it! However I came up with this! : var comindex = address.lastIndexOf(","); var half1 = address.substring(0,comindex); var half2 = address.substring(comindex,full.length); – Hamza Tahir Jun 29 '13 at 06:37
4

With double quotes it is treating it as string

Use it this way

 address.split(/,(?=[^,]*$)/);

Or

This is more readable

 var postcode=address.substr(address.lastIndexOf(","));
Anirudha
  • 32,393
  • 7
  • 68
  • 89
1
var m = /,\s*([^,]+)$/.exec('Some address, city, postcode');
if (m) {
    var postcode = m[1];
}
akonsu
  • 28,824
  • 33
  • 119
  • 194