1

I'd like to change a RegExp constructor, to use case insensitive, but I can't modify the source.

The source calls:

MyExp = new RegExp("xxx","") //Native

Can I create a function that could override that, e.g.

function RegExp(a,b){
  return native.RegExp(a,"i")
}
AndrewC
  • 43
  • 5
  • It's a bad idea to modify native objects. You will change how this behaves not only for your code but *every single other library you are using*. If one of them used to rely on (assumed) case-sensitive matches, you take that away and even well-tested third party code can start behaving erratically. – VLAZ Sep 14 '18 at 21:56
  • Thanks vlaz, but this is for a specific use. – AndrewC Sep 16 '18 at 10:02

2 Answers2

2

This is called monkey patching. Save the old value of the native function in another variable.

(function(nativeRegExp) {
    window.RegExp = function(a, b) {
        return nativeRegExp(a, b || "i"); // default to case-insensitive
    }
})(RegExp);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks Barmar, this is what I am looking for. Didn't know what it is called ;-) – AndrewC Sep 16 '18 at 10:05
  • #1 I've used this technique a few times to intercept and log certain calls--never knew the term for it! – RoccoB Feb 06 '21 at 22:20
  • #2 Sadly, this only works though when the new RegExp constructor is used, not by using a RegExp literal (ie `let re = /ab+c/;`) Wonder if there is some magic to overide that? – RoccoB Feb 06 '21 at 22:22
  • I doubt it. There's no requirement that the literal parser call any public functions. – Barmar Feb 06 '21 at 23:37
0

You could add a new method:

RegExp.i = function(a){
    return new RegExp(a,"i")
} 

var str = "TextToReplace";

var r = new RegExp.i("TEXTTOREPLACE");

var newStr = str.replace(r,"replaced");

console.log(newStr)
Emeeus
  • 5,072
  • 2
  • 25
  • 37