Search code examples
jquerystringtextreplacehref

Jquery: How to find individual sets of numbers in a string of text and add href tags to them


I've got several strings of text with numbers that are meant to connect to other entries in the index (using hashes, as they will be on a page together). For example:

<div class="description"><span>This is some text, which we will reference in entry (330) and also in entry (249).</span></div>

I've been able to get the numbers to show up, separated by a comma, but I'm not able to get them to separate in relation to adding the links, and I'm actually not entirely sure how I should go about wrapping them with a href without replacing the text around them. This is where I'm at so far, but I've hit a wall.

        var val = $("description span").html();
        var numbers = val.match(/\d+/g);
        if (numbers != null) {
           console.log(numbers);
          //here goes the separate and wrap code that eludes me.
        }

intended result:

<div class="description"><span>This is some text, which we will reference in entry (<a href="myindex.html#330">330</a>) and also in entry (<a href="myindex.html#249">249</a>).</span></div>

Thank you for any help.


Solution

  • As said in the comment you are missing a . in your selector, except from that you can try something like:

    $.each(numbers, function(n, t) {
      $(".description span").html($(".description span").html().replace(t, "<a href='#" + t + "'>" + t + "</a>"))
    })
    

    Demo

    var val = $(".description span").html();
    var numbers = val.match(/\d+/g);
    if (numbers != null) {
      $.each(numbers, function(n, t) {
        $(".description span").html($(".description span").html().replace(t, "<a href='#" + t + "'>" + t + "</a>"))
      })
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="description"><span>This is some text, which we will reference in entry (330) and also in entry (249).</span></div>