regex_replacefn.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. function MyReplace($0, $1, $2, $3, $4, offset, input)
  6. {
  7. WScript.Echo("$0=" + $0);
  8. WScript.Echo("$1=" + $1);
  9. WScript.Echo("$2=" + $2);
  10. WScript.Echo("$3=" + $3);
  11. WScript.Echo("$4=" + $4);
  12. WScript.Echo("offset=" + offset);
  13. WScript.Echo("input=" + input);
  14. return $0;
  15. }
  16. var p = /(a)(b)(c)(d)/g;
  17. var s = "xxabcdxxabcdxx";
  18. WScript.Echo(s.replace(p, MyReplace));
  19. var replacefn = function (arg1,arg2,arg3)
  20. {
  21. this.x = 10;
  22. return "xyz";
  23. }
  24. var a = new String("abcdef");
  25. WScript.Echo(a.replace("def",replacefn));
  26. WScript.Echo(x);
  27. replacefn = function(arg) {
  28. // access re.lastIndex inside replace function.
  29. // As per ES6 21.2.5.8, lastIndex should be updated to 0 if global is true
  30. // This should be visible in replace function
  31. WScript.Echo(re.lastIndex);
  32. return "_" + arg;
  33. }
  34. var re = /abc/g;
  35. var str = "abcabc";
  36. re.lastIndex = 3;
  37. WScript.Echo(str.replace(re, replacefn));