Get a part of string from a page source code (information is present in HTML)

216 views Asked by At

How can I look for a keyword in a HTML source code and get a value from the code using Pure JS. There are multiple code tags and I am looking to extract the value 12345 and it can be in any <code> block which doesn't have a unique ID or class. The keyword (word to find in any code tag) to find would be "THIS_IS_WHAT_IAM_LOOKING_FOR".

Example:

HTML source code:

<html>
 <body>
(some HTML goes here)
  <code style="display: none">
wlkdw,dmnewf4oi4j4f4knkf4kjfkfjk;fefiekf;flegelgjelkghjreg;THIS_IS_WHAT_IAM_LOOKING_FOR12345,95849;fefjefefmdl;fljegflegc;evev;evk;evke;v;evirvrkvjrkvuve;vkev;ejv;
 </code>
 
<code style="display: none"> 
fffffffffffekjfekfjekfjrgkrgkjkthjtkhjtkhjtkhjkthp;gkrg2;4l3lgfrgrgkrg9;fefjefefmdl;fljegfleg w;c;evev;evk;evke;v;evirvrkvjrkvuve;vkev;ejv;
     </code> 
 </body>
</html>
1

There are 1 answers

0
Enrique González On

You can use split() to get the part of the string you are interested in, for instance, in your case, i assume you have the mentioned text before the value and a comma after:

const d0 = htmlCode.split('THIS_IS_WHAT_IAM_LOOKING_FOR')[1] // After this text
    .split(',')[0];  // Before this


console.log(d0);

Example working in stackBlitz

https://stackblitz.com/edit/js-hqqvrl?file=index.js

There are probably more elegant ways to do this, but this one should work.