find zip codes in a string using regex in javascript

To find zip codes in a string using regex in JavaScript, you can use the following code snippet:

index.tsx
const text = "My address is 123 Main St, Anytown 45678."; // Example text that contains a zip code
const pattern = /\b\d{5}\b/g;                               // Regex pattern to match 5 digits surrounded by word boundaries

const zipCodes = text.match(pattern);                       // Use the match() method to find all occurrences of the pattern in the text

console.log(zipCodes);                                      // Output: ["45678"]
444 chars
7 lines

In this code, the \b in the regex pattern represents a word boundary, which ensures that the matched digits are surrounded by non-word characters (spaces, commas, periods, etc.). The \d{5} matches five digits in a row, which is the typical format for zip codes in the USA. The g flag at the end of the pattern indicates that we want to find all occurrences of the pattern in the text, not just the first one.

gistlibby LogSnag