user1207013
user1207013

Reputation: 38

regex replace element text

Never seem to master those regex's...

I need to update the total with newVal

<span class="myClass">some text Total (12)</span>

into

<span class="myClass">some text Total (13)</span>

and also without a current value

<span class="myClass">some text Total</span>

into

<span class="myClass">some text Total (13)</span>

oh, and some text can be anything

my code

    newVal = 13;
    $('.myClass').text( $('.myClass').text().replace(???, ???) );

Upvotes: 1

Views: 174

Answers (2)

Pavel Reznikov
Pavel Reznikov

Reputation: 3208

You could wrap counters with span:

<span class="myClass">some text Total (<span>12</span>)</span>

and do like so:

newVal = 13;
$('.myClass span').text(newVal);

Upvotes: 1

Bergi
Bergi

Reputation: 664195

Wrong approach, your code would only return the new string. To set it, use

$('.myClass').text(function(i, old){ 
   return old.replace(/(\s+\(\d+\))?$/, " ("+newVal+")");
})

The regex matches the string end, and (optionally) whitespaces + bracketed number before.

Upvotes: 0

Related Questions