Mr. J
Mr. J

Reputation: 347

Only match single word when using negative lookahead

In Javascript I'm currently using the regular expression:

/^(?!3838\s+REGATTA\s+COURT).*(COURT).*/

I want to entirely avoid matching:

3838 REGATTA COURT

And match:(the addresses will be vary)

5555 REGATTA COURT

However, I only want to match the word "COURT" and not the entire string(which is what my current expression returns).

Also, 5555 REGATTA COURT cannot be removed by specifying an expression such as ^(?!5555\s+REGATTA\s+COURT) because the addresses will vary. I essentially need to avoid matching everything up to "COURT" and then match it.

Upvotes: 0

Views: 98

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521533

Here is one approach using a regex replace all:

var address = "5555 REGATTA COURT ";
var output = address.replace(/^(?!3838\s+REGATTA\s+COURT\b)(.*)\bCOURT\b(.*)/, "$1CT$2");
console.log(address);
console.log(output);

The logic here is to first exclude the address 3838 REGATTA COURT. Then, match and capture everything on either side of the word COURT. Finally, replace with the two capture groups with CT in between them.

We can also try doing this using a callback function:

var address = "5555 REGATTA COURT ";
var output = address.replace(/^(?!3838\s+REGATTA\s+COURT\b)(.*)\bCOURT\b(.*)/, function(m, g1, g2) { return g1 + "CT" + g2; });
console.log(address);
console.log(output);

Upvotes: 2

Christoph Herold
Christoph Herold

Reputation: 1809

If you are worried about the use of $1...$9 in the replacement string, simply check the MDN documentation for the standardized way: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter. The code would then be:

var address = "5555 REGATTA COURT ";
var output = address.replace(/^(?!3838\s+REGATTA\s+COURT\b)(.*)\bCOURT\b(.*)/, function(m, g1, g2) { return g1 + "CT" + g2; });
console.log(address);
console.log(output);

However, the MDN article you mentioned in the comments also has a compatibility chart, which shows that the string syntax is also supported by all modern (and not so modern) browsers.

Upvotes: 0

Related Questions