I need to have array from message that contain ETH address from text.
Example text:
You have ining invoice for 0xc7d688cb053c19ad5ee4f48c348958880537835f from 0xc7d688cb053c19ad5ee4f888848958dd0537835f with time spent 18 : 32 and remark test 1
Expected output:
[
'0xc7d688cb053c19ad5ee4f48c348958880537835f,
'0xc7d688cb053c19ad5ee4f48c348958880537835f'
]
I need to have array from message that contain ETH address from text.
Example text:
You have ining invoice for 0xc7d688cb053c19ad5ee4f48c348958880537835f from 0xc7d688cb053c19ad5ee4f888848958dd0537835f with time spent 18 : 32 and remark test 1
Expected output:
[
'0xc7d688cb053c19ad5ee4f48c348958880537835f,
'0xc7d688cb053c19ad5ee4f48c348958880537835f'
]
Share
Improve this question
edited Mar 24, 2018 at 11:30
Sumit Jha
1,69913 silver badges20 bronze badges
asked Mar 23, 2018 at 14:25
Jignesh AakoliyaJignesh Aakoliya
432 silver badges18 bronze badges
8
- Is there a space after the ETH address? – Sumit Jha Commented Mar 23, 2018 at 14:27
- Does the address have a fixed length, or how can the first one run together with the word "from"? – Arndt Jonasson Commented Mar 23, 2018 at 14:29
- what did you try so far? – guijob Commented Mar 23, 2018 at 14:29
- @SumitJha Yes it has space – Jignesh Aakoliya Commented Mar 23, 2018 at 14:29
- @ArndtJonasson, yes 40 alpha numeric after 0x – Jignesh Aakoliya Commented Mar 23, 2018 at 14:30
2 Answers
Reset to default 3Use match
with following regex (\b0x[a-f0-9]{40}\b)
:
let str = 'You have ining invoice for 0xc7d688cb053c19ad5ee4f48c348958880537835f from 0xc7d688cb053c19ad5ee4f888848958dd0537835f with time spent 18 : 32 and remark test 1'
let resp = str.match(/(\b0x[a-f0-9]{40}\b)/g)
console.log(resp);
Use regular expression/(0x[a-f0-9]{40})/g;
. Here is a fast solution.
const regex = /(0x[a-f0-9]{40})/g;
const str = `You have ining invoice for 0xc7d688cb053c19ad5ee4f48c348958880537835ffrom 0xc7d688cb053c19ad5ee4f888848958dd0537835f with time spent 18 : 32 and remark test 1`;
let m;
let result1 = [];
//Solution 1
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
result1.push(m[0]);
}
console.log(result1);
//Solution 2
let result2 = str.match(regex);
console.log(result2);