dan_vn
dan_vn

Reputation: 55

How can I identify specific numbers in string, and create and populate another span with this number?

I have a span where the value possibilities are: "Showing 1 item" or "Showing x to y of z items". Z can be any positive number.

<div class="result-container">
    <span id="results-label">Showing 1 to 10 of 33 items</span>
</div>

I would like to be able to identify z and place it into a newly created span above this, using jQuery. Please note that "item(s)" is not static due to translations. Desired output:

<div class="result-container">
    <span id="total-results">33</span>
    <span id="results-label">Showing 1 to 10 of 33 items</span>
</div>

The regex I am using is \d+(?=[A-Za-z\s]*$) which seems to work https://rubular.com/r/KrHmLUzEsWGU3P

I have two issues:

  1. For some reason creating and inserting a new span fails:

https://jsfiddle.net/ubte7jx3/

  1. I am unsure how to insert the regex result into the span afterwards.

Upvotes: 0

Views: 38

Answers (1)

dan_vn
dan_vn

Reputation: 55

With some help in the comments I managed to arrive to a solution:

<div class="job-tile-result-container">
    <span id="tile-search-results-label">Showing 1 to 10 of 33 items</span>
</div>


$(document).ready(function() {
    $(".job-tile-result-container").prepend('<span id="total-results"></span>');
    var z_string = document.getElementById("tile-search-results-label").innerHTML;
    var z_results = z_string.match(/\d+(?=[A-Za-z\s]*$)/);
    console.log (z_results);
    document.getElementById("total-results").innerHTML = (z_results);
});

https://jsfiddle.net/r4fd9xcp/5/

Upvotes: 1

Related Questions