Reputation: 191
Can anyone advise on this? I'm trying to create a jquery function that will take the last 3 characters of a string and style them differently. In my case half the font-size.
So in a string like €100.50 the .50 would be smaller
Can someone please point me in the right direction? Or maybe if a plugin/script already exists let me know
Thanks!
Dec
Upvotes: 1
Views: 4347
Reputation: 2405
I often use a formatter like:
HTML
<div id="price"></div>
CSS
.decimal {
font-size:10px;
color:black;
}
JS
function formatPrice(price, containerId, digits) {
var startStr,
endStr,
containerElem = $("#"+containerId);
//cut last specified digits
startStr = price.substr( 0, price.length - digits );
endStr = price.substr( price.length - digits, price.length );
//DOM elements
$("<span/>")
.text(endStr)
.addClass("decimal")
.appendTo(containerElem)
.parent()
.prepend(startStr);
}
var price = "€100.50";
formatPrice(price, "price", 3);
Upvotes: 0
Reputation: 5822
Try this:
function formatString( txt ) {
var i = txt.lastIndexOf( "." );
if( i === -1 ) return txt; // if txt => $10 return
return txt.slice( 0, i ) + "<span class='smaller'>" + txt.slice( i ) + "</span>";
}
Upvotes: 0
Reputation: 171679
The text you want modified needs to be wrapped in another html element to which you can add a class or inline style to make css adjustmets
Assuming this staring html, and using jQuery to get and set the mosified text/html:
<span>€100.50</span>
.
$('span').html(function(idx, oldHtml) {
var startStr = oldHtml.substring(0, oldHtml.length - 3)
var endStr = '<small>' + oldHtml.substring(oldHtml.length - 3) + '</small>'
return startStr + endStr;
});
DEMO: http://jsfiddle.net/vJ63t/
Upvotes: 0
Reputation: 94101
Can someone please point me in the right direction? ...
Using replace
wrap the text in a tag and add a class to style it with CSS:
$el.html( $el.text().replace(/.{3}$/, '<span class="small">$&</span>') );
Demo: http://jsbin.com/epuzag/4/edit
Upvotes: 1
Reputation: 1340
well, does not necessarely involve jquery . you could take the string as a parameters wrap into a styled DIV.
something like:
txt = $("#id").text();
txt = style_string(txt);
function style_string(string){
...
if(){
string = "<div class='class-to-style'>" +string+"</div>"
}....
}
Upvotes: 0
Reputation: 48
maybe you can use a function that get the length of the wanted string and cuts the last 3 letters of it, then put them in a new string into a new tag (span or something) with a wanted class
Upvotes: 1