Home > Back-end >  Regex match just first result or second from HTML table
Regex match just first result or second from HTML table

Time:04-10

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 >
        <td >hello1</td>
        <td >hello2</td>
        <td >hello3</td>
     </td>
   </table>

   <table>
     <td >
       <td >hello1</td>
       <td >hello2</td>
       <td >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

CodePudding user response:

You could do a regular expression something 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 >
        <td >hello1</td>
        <td >hello2</td>
        <td >hello3</td>
     </td>
   </table>

   <table>
     <td >
       <td >hello1</td>
       <td >hello2</td>
       <td >hello3</td>
     </td>
   </table>

  • Related