Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 519
Aminadav Glickshtein Avatar asked Oct 17 '25 00:10

Aminadav Glickshtein


1 Answers

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"'
like image 200
Avinash Raj Avatar answered Oct 18 '25 14:10

Avinash Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!