JSFiddle - React, Tailwind, and code Playground
JavaScript
var str = "foo \"b a \\\" r\" new y 'l o l' foo lol; var x = new 'fo \\' o' ";
var result = str.replace(/(function|new|return|var)?\s+(?=(?:[^\\"']|\\.)*(?:(?:"(?:[^\\"]|\\.)*"|'(?:[^\\']|\\.)*'))*(?:[^\\"']|\\.)*$)/gm,
function($0, $1) { return $1 ? $0 : ''; });
alert(str + "\n" + result);