简体   繁体   中英

jQuery replace - styling numbers

i want to style specific characters inside my <code> tag. so i google and found the .replace() function. but i had problems on styling numbers. i want to change it's style without changing it's text.

here is my code:

HTML

<code> $years = floor($diff / (365*60*60*24)); </code>

JS

('code').each(function()
{
    var text = $(this).text(); 
    var setan = text.replace(/\d+/g,'<int>'+'\d'+'</int>');
    $(this).html(setan); 
});

the output is $years = floor($diff / (d*d*d*d));

i want to make it at least like $years = floor($diff / (<b>d</b>*<b>d</b>*<b>d</b>*<b>d<b>));

Better to use css class to style the element like

 $('code').html(function() { var text = $(this).text(); return text.replace(/\\d+/g, '<span class="d">' + 'd' + '</span>'); }); 
 code span.d { font-weight: bold; color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <code> $years = floor($diff / (365*60*60*24)); </code> 

i want to make it at least like $years = floor($diff / (<b>d</b>*<b>d</b>*<b>d</b>*<b>d</b>));

Try substituting <b></b> for <int></int> at replacement text , utilizing .html(function(index, html){})

 $("code").html(function(_, html) { return html.replace(/\\d+/g,"<b>d</b>"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <code> $years = floor($diff / (365*60*60*24)); </code> 

As I have understood, you want numbers to be presented there, but not d letters.

You can use capture groups for replacing.
That's how you can do this:

 $("code").each(function() { var text = $(this).text(); $(this).html(text.replace(/(\\d+)/g, '<int>$1</int>')); // here you can place any tags }); 
 int { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <code>$years = floor($diff / (365*60*60*24));</code> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM