Navin Rauniyar
Navin Rauniyar

Reputation: 10525

What's the best way to use back references?

In some \1 will work and in some $1 in online regex builder.

Does both way works in every javascript engine?

Upvotes: 2

Views: 111

Answers (2)

user2864740
user2864740

Reputation: 61875

Only one way works in JavaScript, and it differs if the back-reference is in the regular expression (\n) or the replacement value ($n).

See MDN Regular Expressions:

[In a regular expression] where n is a positive integer, [\n refers to] a back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses).

For example, /apple(,)\sorange\1/ matches 'apple, orange,' in "apple, orange, cherry, peach."

..

The \1 and \2 in the pattern match the string's last two words. Note that \1, \2, \n are used in the matching part of the regex. In the replacement part of a regex the syntax $1, $2, $n must be used, e.g.: 'bar foo'.replace( /(...) (...)/, '$2 $1').

That way is the correct way in JavaScript; different regular expressions may work differently, but such is irrelevant to JavaScript code which works as stated above.

Upvotes: 3

Braj
Braj

Reputation: 46841

Backreferences, cannot be used inside a character class. The \1 in a regex like (a)[\1b] is either an error or a needlessly escaped literal 1. In JavaScript it's an octal escape.

It's better explained at Using Regular Expressions with JavaScript - regular-expressions.info

Upvotes: 0

Related Questions