Home > database >  Referencing part of the url from html href element in javascript
Referencing part of the url from html href element in javascript

Time:12-10

I'm new to programming and have run into what is probably a beginner problem. I'm not quite sure how to phrase this question but I am basically trying to figure out how to reference part of a URL for a userscript I'm modifying.

Here's the website HTML:

  <div >
    <h2 >
      <a href="/example/12345">Title</a>

I'm trying to refer to the "12345" part. "/example/12345" would also work. Here's the relevant part of the code:

  function selectFromBlurb(blurb) {
    return {
      reference: selectTextsIn(blurb, "header .heading a:first-child")
    };
  }

Currently the code is referring to the Title. I tried a bunch of things but as an amateur I couldn't figure it out. Thanks for any help!

CodePudding user response:

You could do

reference: blurb.querySelector(".header .heading a:first-child").href.split('/').at(-1)

CodePudding user response:

I'm not sure I understood your requirement but I guess you want to return "12345" as a reference. If so, please try this.

function selectFromBlurb(blurb) {
  var refer = blurb.substring(0, blurb.lastIndexOf("/")   1);
return {
  reference: selectTextsIn(refer, "header .heading a:first-child")
};
  console.log(reference)

}

CodePudding user response:

function selectFromBlurb(blurb) {
  var params = blurb.split("/");
return {
  reference: selectTextsIn(params[0], "header .heading a:first-child")
};
  • Related