'Regex match just first result or second from HTML table

I'm using regex in-app script javascript. I try to get just the first value or the second value from each table but not work.

   <table>
      <td class="bar">
        <td class="center">hello1</td>
        <td class="center">hello2</td>
        <td class="center">hello3</td>
     </td>
   </table>

   <table>
     <td class="bar">
       <td class="center">hello1</td>
       <td class="center">hello2</td>
       <td class="center">hello3</td>
     </td>
   </table>

my code regex: /(?<=<td class=\"center\">).*?(?=<\/td>)/gi

this code selects all values Hello. I want just select Hello1 from the first table td and second table td. I remove global but give me just the first td from the first table.

the hello value is dynamic not fixed.

enter image description here



Solution 1:[1]

You could do a regular expression something like this which retrieves the text you expect...

regular expression run results

Essentially matching the tags by excluding <> characters within the tag.

However I think an easier and less error prone way to do this in JavaScript and DOM is to use querySelectorAll instead, for example...

let c = document.querySelectorAll('td:nth-of-type(2)');

console.log(Array.from(c).map(i => i.innerText));
   <table>
      <td class="bar">
        <td class="center">hello1</td>
        <td class="center">hello2</td>
        <td class="center">hello3</td>
     </td>
   </table>

   <table>
     <td class="bar">
       <td class="center">hello1</td>
       <td class="center">hello2</td>
       <td class="center">hello3</td>
     </td>
   </table>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dezfowler