Reputation: 3085
I have HTML:
<div id="ingredients">
<p itemprop="ingredients">30 dag beans</p>
<p itemprop="ingredients">around 1,5 liter of water </p>
</div>
I have javascript:
$('#ingredients').html(
function (i, text) {
return text.replace(/>([\d,]+)/g, '<span>$1</span>');
});
The regular expression should replace the first number with 'test' because before the number there is > tag. It should not replace the second number (we use , for number decimals) because there is space before.
So I'd like it to replace only the ingredients that have number at the beggining of the paragraph, not the ones that have numbers in the middle of the paragraph.
Why does it not work? If I omit the > in the regex it works, but replaces all the numbers even the ones in the middle of the sentance.
Upvotes: 2
Views: 66
Reputation: 87203
The problem with your regex is that it is also replacing >
of the <p>
.
This can be solved by using
return text.replace(/>([\d,]+)/g, '><span>$1</span>');
^
JSfiddle Demo and Regex101 Demo
but there is better way to do this.
Steps:
<p>
elements inside the container #ingredients
trim
the spaces^([\d,]+)
to extract the numbers that are at the beginning of the string and replace it by <span>$1</span>
, $1
here is the number that is captured by the regex.Regex Explanation:
^
: Start of the line([\d,]+)
: First capturing group. Matching one or more occurrences of number and/or comma in any sequence. This captured group can be accessed by using $1
.Demo and Regex101 Demo
// Iterate over all the paragraph elements inside the container
$('#ingredients p[itemprop="ingredients"]').html(function(index, text) {
// text == innerText of the current `p` element
// The value returned will be replaced to the innerHTML
// First trim the string to remove leading and trailing spaces
return text.trim().replace(/^([\d,]+)/, '<span>$1</span>');
});
span {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="ingredients">
<p itemprop="ingredients">30 dag beans</p>
<p itemprop="ingredients">around 1,5 liter of water</p>
</div>
Upvotes: 6