简体   繁体   中英

Regex matching substring inside curly brackets inside script tag

I'm trying to get the information between the brackets, but my pattern doesn't find a match.

The pattern I'm using is

/var\scool=(.*);<\/script>/;

The sample text:

<script>
  var cool={
  //stuff in here
  };
</script>
/var\scool\=(.*);\s<\/script>/s

The regex you have has a dot with a * quantifier ( .* ) that matches zero or more characters other than a newline, as many as possible . In JavaScript regex, to match any character including a newline you can use [^] or [\\s\\S] or [\\d\\D] or [\\w\\W] .

The other problem is that there is whitespace between the ; and </script> , thus a \\s* is necessary.

Use

/var\scool=([\s\S]*);\s*<\/script>/

See the regex demo

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