开发者

Changing a character in a class

I would like to amend the last character of a string in a particular class. That is, I would like to change the comma to a full-stop in list items belonging to the class last (li.last). For example:

<li>one,</li>
<li>two,</li>
<li>three,</li>
<li class="last">four,</li>

change to:

<li class="l开发者_StackOverflowast">four.</li>

Is there a simple way to do this?


You can use the .text overload that takes a function, which is useful if you have many such elements:

$('li.last').text(function(i, text){
        return text.replace(/,$/, '.');
});

Example: http://jsfiddle.net/xVHKd/

Note that you can also use the :last-child selector: $('li:last-child').


$('.last').each(function(){

   var text = $(this).text();
   text = text.substr(0,text.length-1);  
   text = text+'.';

   $(this).text(text);

});


$(".last").text($(".last").text().replace(",","."));

but I'm not sure if this is a good solution when there are any child elements in the element with the class last


With jQuery:

var $last = $('.last');
$last.html($last.html().replace(',' , '.'));

This will replace all "," to "." Hope that helps.


I would say

$('li.last').text($('li.last').text().replace(',', '.')


Something like this:

var elem = $('li.last');
elem.text(elem.text().replace(/,^/, "."));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜