0
let a =  `<script crossOrigin="anonymous" src="//example.com/index.js"></script>`

let regex = new RegExp(
            `<script(.*?) src="` + '//example.com/index.js' + `"></script>`, 'g')
let replacementString = 'document.cookie=e.replace(/[^+#$&^`|]/g,encodeURIComponent).replace("(","%28").replace(")","%29")+"="+t.replace(/[^+#$&\/:<-\[\]-}]/g,encodeURIComponent)+(r.domain?";domain="+r.domain:"")+(r.path?";path="+r.path:"")+(r.secure?";secure":"")+(r.httponly?";HttpOnly":"")'
b = a.replace(regex, replacementString)

The b result is:

document.cookie=e.replace(/[^+#<script crossOrigin="anonymous" src="//example.com/index.js"></script>^`|]/g,encodeURIComponent).replace("(","%28").replace(")","%29")+"="+t.replace(/[^+#<script crossOrigin="anonymous" src="//example.com/index.js"></script>/:<-[]-}]/g,encodeURIComponent)+(r.domain?";domain="+r.domain:"")+(r.path?";path="+r.path:"")+(r.secure?";secure":"")+(r.httponly?";HttpOnly":"")

while the expected result is the replacementString value as is.

Why is the result different?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Blake
  • 7,367
  • 19
  • 54
  • 80
  • You need to escape the `replacementString` before passing it into the `a.replace()` You may find this post useful https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex – Tunji Oyeniran Sep 05 '19 at 07:49

1 Answers1

1

There are two issues:

JS fixed snippet:

let a = '<script crossOrigin="anonymous" src="//example.com/index.js"></scrpit>';

let regex = new RegExp(
            '<script(.*?) src="' + '//example.com/index.js' + '"></scrpit>', 'g');
let replacementString = 'document.cookie=e.replace(/[^+#$$&^`|]/g,encodeURIComponent).replace("(","%28").replace(")","%29")+"="+t.replace(/[^+#$$&\/:<-\[\]-}]/g,encodeURIComponent)+(r.domain?";domain="+r.domain:"")+(r.path?";path="+r.path:"")+(r.secure?";secure":"")+(r.httponly?";HttpOnly":"")';
let b = a.replace(regex, replacementString);
document.body.innerHTML = "<pre>" + b + "</pre>";
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563