Trying to strip out the extra addressee from an address string. In the example below, dba bobs
is the targeted string to remove.
JavaScript
x
5
1
const NOT_EXTRA_ADDRESSEE = /^(?!.*(attn|co|dba|fka|dept).*n).*n/gim;
2
3
"bobs burgers dba bobs dinnern100 Oceanside drivennashville, tn 37204"
4
.replace(NOT_EXTRA_ADDRESSEE, "");
5
The above yields:
JavaScript
1
4
1
bobs burgers dba bobs dinner
2
100 oceanside drive
3
nashville tn 37204
4
When the desired is:
JavaScript
1
4
1
bobs burgers
2
100 oceanside drive
3
nashville tn 37204
4
What am I doing wrong? Sometimes the input has a ‘n’ before the ‘dba’.
Advertisement
Answer
You can simplify your regex to: /b(attn|co|dba|fka|dept)b.*/gm
Test here: https://regex101.com/r/TOH9VV/2
JavaScript
1
22
22
1
const regex = /b(attn|co|dba|fka|dept)b.*/gm;
2
3
// Alternative syntax using RegExp constructor
4
// const regex = new RegExp('\b(attn|co|dba|fka|dept)\b.*', 'gm')
5
6
const str = `bobs burgers dba bobs
7
100 Oceanside drive
8
nashville, tn 37204
9
10
bobs burgers dba bobs
11
100 attn Oceanside drive
12
nashville, tn 37204
13
14
bobs burgers dba bobs
15
100 Oceanside depth drive
16
nashville, tn fka 37204`;
17
const subst = ``;
18
19
// The substituted value will be contained in the result variable
20
const result = str.replace(regex, subst);
21
22
console.log('Substitution result: ', result);
EDIT: Included suggestion of user Cary Swoveland in the comments.