'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:
- For some reason creating and inserting a new span fails:
https://jsfiddle.net/ubte7jx3/
- I am unsure how to insert the regex result into the span afterwards.
Solution 1:[1]
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);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dan_vn |
