find ethereum addresses in a string using regex in javascript

To find Ethereum addresses in a string using regex in JavaScript, you can use the following regular expression:

index.tsx
/(0x[a-fA-F0-9]{40})/
22 chars
2 lines

This regex pattern matches any string that starts with 0x and is followed by 40 hexadecimal characters. This pattern corresponds to the format of Ethereum addresses.

To use this regular expression in JavaScript, you can use the exec() method on a string to match the first occurrence of the pattern, or the match() method to match all occurrences of the pattern.

Here's an example of how to use exec():

index.tsx
const string = 'Here is an Ethereum address: 0x1234567890123456789012345678901234567890';
const pattern = /(0x[a-fA-F0-9]{40})/;

const result = pattern.exec(string);
if (result) {
  console.log('Found Ethereum address:', result[0]);
} else {
  console.log('No Ethereum address found');
}
289 chars
10 lines

In this example, the pattern variable contains the regular expression pattern, and the exec() method is used to match the pattern against the string variable. If a match is found, the result is an array containing the matched string as the first element.

gistlibby LogSnag