I'm struggling to get a javascript regex to work on some edge cases.
The goal is to take a string with some js code and rewrite a function, using the original arguments.
A simple case is: 'apples("a", 1, {value: 2})'
would become 'bananas("a", 1, {value: 2})'
.
However it's a bit more complicated when you deal with real code. For example replacing a function for a "promisified" version of that function with nested functions, and return statements, and multiline objects:
string = 'function(){
return Request({
json:true,
url: "http://google.com"
method: "GET"
})
}'
In this case the result I expect is:
string = 'function(){
return newPromiseFunction({
json:true,
url: "http://google.com"
method: "GET"
}).then(function( res ){ console.log(res) })
}'
So my best attempt is:
var substring = string.match(/\return\sRequest+\(.+?\)/g );
var argsString = substring[0].match( /\((.*?)\)/ );
var result = 'return newPromiseFunction('+ argsString + ').then(function( res ){ console.log(res) })}'
However this code only works if there are no line breaks nor tabs in the argument. But a multiline object (as above) will fail.
Is there a simple fix to my regex above? Is there a simpler way to do it? Is regex even the best way to approach this?