简体   繁体   中英

How to create a Regexp To find all strings in JS files (or JSON)

I am trying to extract all strings in js files. (to use the regexp in sublime text "search in all files")

For example, this is a one of the text files:

a='string1'
b='string2'
c="string3"
alert("string\"4")
alert('string\'5')

So, I have this RegExp:

/('.*?')|(".*?")/

And I found This:

['string1'].['string2',"string3"]

But I need also:

["string4","string5"]

How I do that?

(I am searching for RegExp solution - One RegExp sentence)

One more thing: The best solution is, if it also possibile to ignore all JS comments, inside the files. (To not extract JS strings, in comments)

Thank you.

You could try the below regex.

(['"])(?:\\\1|(?!\1).)*?\1

DEMO

  • (['"]) captures ' or " quotes and stored it into group index 1.
  • (?:\\\\\\1|(?!\\1).) This allows escaped character ( character which was captured by the group index 1 ). OR not of the captured character zero or more times.
  • \\1 And it must be ended by the character which was captured by the group index 1.
  • It also matches the strings like "string'5'" or 'string"5"'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM