Access to RegExp using JSFuck convention

Viewed 201

I want to replace some characters in string e.g.

console.log( 
    "truefalse".replace("e","E")
)

but using jsfuck convenction where only 6 chars are allowed: []()!+, here for increase readability also JS strings with letters a-z and A-Z and numbers 0-9 are allowed (because it is easy to convert such strings to 6-char jsf code). So I can write it as follows

console.log(
  "truefalse"["replace"]("e","E")
)

but in above code I use forbidden character - comma: ,. So I use technique of calling function with 2 (and more) paremeters discovered by trincot here as follows

console.log(
  "truefalse"["split"]()["concat"]([["e"]["concat"]("E")])
    ["reduce"](""["replace"]["apply"]["bind"](""["replace"]))
)

Now I want to use regular expression in replace function and write code using above restrictions

console.log(
  "truefalse"["replace"](/e/g,"E")
)

but I don't know what to do with regexp part /e/g ?. It is possible to do it without using any kind of 'eval' (where string is interpreted as code)?

1 Answers

I don't see a way to get access to the RegExp constructor without evaluating code, like with the Function constructor:

""["replace"]["constructor"]("return RegExp")()

But consider this

  • If you need to replace multiple occurrences, you can use the replaceAll method with a string for first argument
  • The methods match and matchAll can be used with a string argument, and a RegExp object will be created for that string on the fly, as if you had called .match(RegExp(str))

So if for instance you need to split a string in chunks of four characters, you can use .matchAll("...."). There is just two things to do more:

  • As matchAll returns an iterator, you need to make an array from it; like with Array.from.
  • As you don't have direct access to the Array variable, you could use [].constructor instead.
  • The returned chunks are in a nested array, which needs flattening. You could chain a .flat() call for that.

So that becomes

console.log(
  []["constructor"]["from"]("abcdefghijkl"["matchAll"]("...."))["flat"]()
);

Related