Home > Net >  JQuery get the text inside an element using special characters
JQuery get the text inside an element using special characters

Time:12-10

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 >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.

CodePudding user response:

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>

CodePudding user response:

To get the number inside h6 and wrap it in a div, you can use this code:

// Select the h6 element
var h6 = $('h6');

// Get the text inside the h6 element
var text = h6.text();

// Use a regular expression to find the number inside square brackets
var numberRegex = /\[(. ?)\]/;
var match = numberRegex.exec(text);

// If a match was found, wrap the number in a div with the "number" class
if (match) {
  var number = match[1];
  var numberDiv = $('<div>', {
    class: 'number',
    text: number
  });
  h6.html(numberDiv);
}

First, select the h6 element and get its text. Then use a regular expression to find the number inside square brackets. If a match is found, create a div element, set its class attribute to number, and set its text to the number we found. Replace the contents of the h6 element with the div element.

CodePudding user response:

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 ></div>
</div>

  • Related