skip to Main Content

I’m trying to isolate a number inside a h6 tag and wrap it in a div.

<h6>[123-4] My Title</h6>

To

<h6>
   <div class="number">123-4</div>
   My Title
</h6>

How can I select and wrap the number? .text() seems to select everything and using a regex would be difficult as the title text could also contain dashes.

2

Answers


  1. A dirty solution would be to use a simple replace. By default replace ONLY replaces the first instance. If you are sure that the number will be wrapped in brackets, then using a replace will only replace the first instances of each bracket.

    $(document).ready(function() {
      $("h6").each(function() {
        $(this).html($(this).html().replace("[", "<div class='number'>").replace("]", "</div>"))
      });
    });
    .number {
      display: inline-block;
      color: red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <h6>[123-4] My [Titl]e</h6>
    Login or Signup to reply.
  2. a regex would be difficult as the title text could also contain dashes

    You have to identify the pattern that will allow you to discern which part of the text is your "number" and which is the title. It looks like the square brackets will surround then number? In which case the regex is simple:

    $(document).ready(function() {
        let text=$('h6').text();
        let $target = $('#result');
        let $number = $('.number');
        
        const re = /[(.+)](.+)/;
        let matched = text.match(re);
        
        $number.text(matched[1]);
        $target.append(matched[2].trim());
        
        // console.log('text', text);
        // console.dir(matched);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <h6>[123-4] My Title</h6>
    
    Result:
    <div id="result">
        <div class="number"></div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search