简体   繁体   中英

How to extract a string from html body content and add as a javascript variable

I would like to use javascript to extract 1234 from the html body below and add this 1234 as a javascript variable. I will be adding this script into multiple html pages with a mixture of text, images, etc. However, the links are all the same except for the id part which will change with each page. There will be duplicates of the same links on a page, but I only need to add one instance of the id 1234 as a javascript variable. Thank you for your help.

Example of basic HTML

  <html>
<body>
blah blah <p>
<a href="https://example.com/tracking.php?id=1234">example link</a>
<p>
more blah blah <a href="https://example.com/tracking.php?id=1234">duplicate link</a>
<p>
even more blah blah
</body>
</html>

I created a function that brings you a solution.

function getparams(param, elID) {
  const href = document.getElementById(elID).getAttribute('href');
  const params = href.split("?")[1];
  const allParams = params.split('&'), paramName, i;
  for (i = 0; i < allParams.length; i++) {
    paramName = allParams[i].split('=');
    if (paramName[0] === param) {
      return paramName[1] === undefined ? true : decodeURI(paramName[1]);
    }
  }
}

Then you can use it like this:

 function getparams(param, elID) { let href = document.getElementById(elID).getAttribute('href'); let params = href.split("?")[1]; let allParams = params.split('&'), paramName, i; for (i = 0; i < allParams.length; i++) { paramName = allParams[i].split('='); if (paramName[0] === param) { return paramName[1] === undefined? true: decodeURI(paramName[1]); } } } console.log(getparams("id", "myLink")) console.log(getparams("anyParam", "myLink"))
 <a id="myLink" href="https://example.com/tracking.php?id=1234&anyParam=124000">example link</a>

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