find zip codes in a string using regex in typescript

To find zip codes in a string using regular expressions in TypeScript, you can use the following code snippet:

index.ts
const inputString = "My address is 123 Main St, Anytown, USA 12345";
const zipRegEx = /\b\d{5}\b/g;
const zipCodeArray = inputString.match(zipRegEx);
console.log(zipCodeArray); // Output: ['12345']
198 chars
5 lines

Explanation:

  • The inputString is the string you want to search for zip codes.
  • The zipRegEx is a regular expression pattern that matches zip codes in the format of 5 digits bounded by word boundaries (i.e., space or punctuations). \b is a boundary anchor and \d is a digit character class. {5} indicates that we want to match exactly 5 digits. g is a global flag that specifies we want to match all occurrences in the input string.
  • The match method of the String object searches for all matches of the regular expression in the input string and returns an array of matches. If there is no match, it returns null.
  • The zipCodeArray variable holds the resulting array of zip codes in the input string, or null if nothing is found.
  • The console.log statement displays the contents of the zipCodeArray.

Note that this regex pattern may not match all zip code formats, especially international ones. You might need to adjust the pattern accordingly to your use case.

gistlibby LogSnag