0

I'm trying to switch some regex done in PHP to Javascript and didn't realize that they aren't the same syntax. I'm clearly no regex pro, so I'm very confused as to what exactly isn't working correctly. **Please also note that the html code below is returned as a string.

This regex code works for PHP, but not Javascript (although I have it in a javascript .match)

string.match(/<table(?:.*)class="tblclass"[\s\S]*?class="tblclass"[\s\S]*?<td(?:.*)>[\s\S]*?\K(\d+)/)

Also tried

response.match(/\s*table(?:.*)class="tblclass"[^>]*>[\s\S]*?class="tblclass"[\s\S]*?<\s*td[^>]*>[\s\S]*?\K(\d+)/);

I am trying to get the number (54) from the string below. This includes all the white space and line breaks


                                        <table class="tblclass" cellpadding="0" cellspacing="0"><tr><td>
                                        <table class="tblclass" cellpadding="0" cellspacing="0" width="50">
                                                 <tr  style="color:black;">
                                                        <td  background="/images/websiteimg.jpg"                           style="background-repeat: no-repeat;"     height="38" width="50" >
                                                        54
                                              </td>
                                                </tr>
                                        </table></td>
                                        <td class="numclass">Acceptable</td>
                                        </tr></table>

Using https://regex101.com/ and pasting what I have above, the PHP version works, but the Javascript version 'does not match the subject string'.

Can anyone maybe point me in the right direction for getting the differences?

Keith
  • 770
  • 1
  • 6
  • 17
  • JS regex does not support `\K`: use capturing groups instead to get what you need or what you need to keep during replacement. – Wiktor Stribiżew May 23 '19 at 16:58
  • @WiktorStribiżew Thanks Wiktor, Although I'm still not 100% sure how to solve it, knowing that \K was messing it up helped. I was able to use javascript to get the 54 from the html string using - matches[0].substr(-3, 3).trim(). Ugly, but it works. – Keith May 23 '19 at 20:29
  • [This is the expression](https://regex101.com/r/Q2VQ0s/1) you need to use in JS. Just grab `matches[1]` after you use `var matches = /regexhere/.exec(string)`. However, to parse HTML, you should consider using DOM. – Wiktor Stribiżew May 23 '19 at 20:32

0 Answers0