2

I'm trying to write a regex in javascript to identify string representations of arbitrary javascript functions found in json, ie. something like

{
  "key": "function() { return 'I am a function'; }"
}

It's easy enough to identify the start, but I can't figure out how to identify the ending double quotes since the function might also contain escaped double quotes. My best try so far is

/"\s*function\(.*\)[^"]*/g

which works nicely if there are no double quotes in the function string. The end of a json key value will end with a double quote and a subsequent comma or closing bracket. Is there some way to retrieve all characters (including newline?) until a negated pattern such as

not "/s*, and not "/s*}

... or do I need to take a completely different approach without regex?

Here's is the current test data I'm working with: http://regexr.com/39pvi

1 Answer 1

1

Seems like you want something like this,

"\s*function\(.*\)(?:\\.|[^\\"])*

It matches also the inbetween \" escaped double quotes.

DEMO

Sign up to request clarification or add additional context in comments.

4 Comments

it's not working if there is \n in the body of the function like this: "function() { return 'hello \n fun ction stuff'; }"
it works, see regex101.com/r/oY5jU1/1 . [^"\\]* would match newline characters also.
if there is any \n present in this () block then he need to change the regex like "\s*function\([\S\s]*?\)(?:[^"\\]|\\")*
You can switch the two parts and leave out the \\: "\s*function\(.*\)(?:\\"|[^"])*". See regex101.com/r/oY5jU1/3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.