替换元素中的文本

Replace text in element

本文关键字:文本 元素 替换      更新时间:2023-09-26

我有以下内容:

<li class="product_promo promo_code_227598" id="discount_14902941">
    <img src="/wcsstore/ConsumerDirectStorefrontAssetStore/images/discount.gif" alt="" align="middle">
    -2-for-10-
</li>

我只想替换文本的第一个和最后一个字符。

我尝试了以下内容,但它取代了元素的内容:

$(this).text($(this).text().replace(/^-+|-+$/g,''));

我也尝试过以下内容,但第一个破折号没有被替换。

$(this).html($(this).html().replace(/^-+|-+$/g,''));
var len = $.trim($("li").text());
var res = len.slice(1,len.length-1);
$("li").contents().last()[0].textContent = res; // this way you can append the text without affcet the html tag

DEMO

尝试

$(this).html($(this).html().replace(/^[-+]|[-+]$/g,''));

试试这个:

$(this).text(function(i, v){
  return v.replace(/^-+|-+$/g,'');
});

请注意:这只适用于jQuery 1.4及更高版本。