Closed Bug 28686 Opened 25 years ago Closed 25 years ago

String.prototype.replace incorrectly handles substing matches preceded by "\"

Categories

(Core :: JavaScript Engine, defect, P3)

x86
Windows 98
defect

Tracking

()

VERIFIED FIXED

People

(Reporter: cerberus40, Assigned: rogerl)

References

Details

(Keywords: js1.5)

From Bug Helper: User-Agent: Mozilla/5.0 [en-CA] (Windows_98; I) BuildID: 2000012520 If the String.replace method uses substring match properties ($1, $2, etc.) preceded by a backslash character ("\"), the match is replaced by the literal "\$n" Reproducible: Always Steps to Reproduce: 1. Place this on a page and load it: <pre><script> var myString="\"We're not in Kansas anymore,\" said Dorothy."; document.writeln(myString.replace(/(['"])/g, "\\$1")); document.writeln(myString.replace(/(['"])/g, "\/$1")); </script></pre> 2. The first line replaces the quotes with "\$1". The second line correctly replaces the quotes with "/q" where q is a single or double quote. Actual Results: \$1We\$1re not in Kansas anymore,\$1 said Dorothy. /"We/'re not in Kansas anymore,/" said Dorothy. Expected Results: \"We\'re not in Kansas anymore,\" said Dorothy. /"We/'re not in Kansas anymore,/" said Dorothy.
Caused by older code that is escaping the $ when preceded by a \. Here's a patch : Index: jsstr.c =================================================================== RCS file: /m/pub/mozilla/js/src/jsstr.c,v retrieving revision 3.25 diff -u -r3.25 jsstr.c --- jsstr.c 2000/02/11 22:16:55 3.25 +++ jsstr.c 2000/02/25 01:13:12 @@ -998,10 +998,16 @@ uintN num, tmp; JSString *str; - /* Allow a real backslash (literal "\\") to escape "$1" etc. */ JS_ASSERT(*dp == '$'); - if (dp > rdata->repstr->chars && dp[-1] == '\\') - return NULL; + + /* + * Allow a real backslash (literal "\\") to escape "$1" etc. + * Do this for versions less than 1.5 (ECMA 3) only + */ + if (cx->version != JSVERSION_DEFAULT && + cx->version <= JSVERSION_1_4) + if (dp > rdata->repstr->chars && dp[-1] == '\\') + return NULL; /* Interpret all Perl match-induced dollar variables. */ res = &cx->regExpStatics;
Status: UNCONFIRMED → ASSIGNED
Ever confirmed: true
Keywords: js1.5
checked in.
Status: ASSIGNED → RESOLVED
Closed: 25 years ago
Resolution: --- → FIXED
Added Testcase ecma_3/RegExp/regress-28686.js. cerberus40: Nice catch! You may be interested to know that String.prototype.quote() already does what it looks like you're trying to do... js> var str = 'foo "bar" baz'; js> str.quote(); "foo \"bar\" baz" js> Either way, thanks for the bug report. Marking Verified.
Status: RESOLVED → VERIFIED
Blocks: 291429
You need to log in before you can comment on or make changes to this bug.