Skip to content

Instantly share code, notes, and snippets.

@ajardin
Created September 20, 2016 16:18
Show Gist options
  • Save ajardin/f7ee1c54f6e0b46ac3d971ef5a1dd8db to your computer and use it in GitHub Desktop.
Save ajardin/f7ee1c54f6e0b46ac3d971ef5a1dd8db to your computer and use it in GitHub Desktop.
Update a JavaScript function body without overwriting the whole code.
/*
In the code below, "form_validation" is a JavaScript function provided by a third-party component. This function validates
and then sends the form values. Since these two behaviors are linked, it's impossible to only validate the form in this state.
But we can update the function without overwriting the whole code.
*/
if (typeof form_validation === 'function') {
var definition = form_validation.toString()
.replace(/myForm\.submit\(\);?/, 'return true;');
var functionParameters = definition.substring(definition.indexOf('(') + 1, definition.indexOf(')')).split(',');
var functionBody = definition.substring(definition.indexOf('{') + 1, definition.lastIndexOf('}'));
window.form_validation = new Function(functionParameters, functionBody);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment