Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find last occurrence of comma in a string using regex in javascript

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!

like image 342
Hamza Tahir Avatar asked Dec 02 '22 22:12

Hamza Tahir


1 Answers

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.

like image 162
nnnnnn Avatar answered Dec 21 '22 23:12

nnnnnn