Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap a sub-string containing a dollar sign with a <strong> using jQuery

Tags:

jquery

I have this HTMl from a db, <p>$10 remaining of $100 budget</p>

I'd like to wrap the $10 with a <strong> tag as below.

The dollar amount could change to be more than 2 digits, and I'd like to wrap the entire amount.

The result I'm seeking using jQuery/JS is...

<p><strong>$10<strong> remaining of $100 budget</p>

Thank you.

like image 924
kinet Avatar asked Nov 19 '25 18:11

kinet


2 Answers

You can do :

$('p').html(function(_, old){
     return old.replace(/(\$\d+) /, '<strong>$1</strong> ');
})

Fiddle : http://jsfiddle.net/gEfzs/

like image 127
Karl-André Gagnon Avatar answered Nov 21 '25 08:11

Karl-André Gagnon


You can do this all with string manipulation. DEMO Someone else could probably do this more efficiently with Regex but hey this works fine.

var priceStr = "<p>$10 remaining of $100 budget</p>";
// remove <p>
priceStr     = priceStr.substr("<p>".length, priceStr.length);
// convert to array and get `$10` as first element
var priceStrArr  = priceStr.split(' ');
// replace first element in array `$10` with wrapping string
priceStr = priceStr.replace(priceStrArr[0], '<p><strong>'+priceStrArr[0]+'</strong>');
// output
$('#thingy').html(priceStr);
like image 39
Fresheyeball Avatar answered Nov 21 '25 07:11

Fresheyeball



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!