Closed Bug 275544 Opened 20 years ago Closed 20 years ago

Javascript RegExp: escaped closing square bracket in character class not recognised

Categories

(Firefox :: General, defect)

1.0 Branch
x86
Windows XP
defect
Not set
minor

Tracking

()

VERIFIED INVALID

People

(Reporter: bugzilla, Assigned: bugzilla)

References

Details

First: apologies for the double-submit, I hit enter by mistake.

Problem:

Trying to write a simple Javascript function to escape strings in a
regex-compatible way, so eg.

'[foo]' becomes '\[foo\]'

I wrote a pattern like this:

var pattern = new RegExp( '([\]\[\}\{\^\$\*\+\?\.\(\)\|])', 'g' );

And nothing happens. But take the escaped closing square bracket out and it
works fine (except obviosuly, it ignores closing square brackets!). Seems like
it's interpreting the cloing bracket as if it's closing the character class.

Here's the function (broken in Firefox, works in IE:

function regex_escape( subject ){

	var output = '';

	var pattern = new RegExp( '([\]\[\}\{\^\$\*\+\?\.\(\)\|])', 'g' );
	pattern.multiline = true;

	output = subject.replace( pattern, '\\$1' );

	return output;

} // END function regex_escape()

As a PS, you'll also find that if curly braces are entered in order '\{\}' it
will think it's an enumeration -- so you have to put them in reverse order
'\}\{', which works.
*** Bug 275543 has been marked as a duplicate of this bug. ***
(In reply to comment #0)
> '[foo]' becomes '\[foo\]'

If I understand right, it should be '\\[foo\\]'
Exactly right: myRegExp = new RegExp("\\t"); is the same as myRegExp = /\t/;. I
was going to quote the spec, but "If pattern must contain an escape sequence to
be recognised by RegExp, the "\" character must be escaped within the
StringLiteral to prevent its being removed when the contents of the
StringLiteral are formed" maybe isn't all that explanatory.
Status: UNCONFIRMED → RESOLVED
Closed: 20 years ago
Resolution: --- → INVALID
Status: RESOLVED → VERIFIED
You need to log in before you can comment on or make changes to this bug.