使用jQuery隐藏句子中的特定单词

时间:2013-07-03 06:49:35

标签: jquery regex

我知道jQuery,但我在RegEx中有点菜鸟。

<span class="subscription-price"> 
    <span class="amount">$15</span> / month with a 29-day free trial
</span>

我希望隐藏29天免费试用(带有XX天免费试用版),是否有可能使用jQuery RegEx?或任何其他方法?

我想要的结果是

 "$15 / month" Instead of "$15 / month with a 29-day free trial"

提前致谢, 阿贾伊

5 个答案:

答案 0 :(得分:2)

完全删除单词:

$('.subscription-price').each(function(){
    var text = $(this).find('.amount')[0].nextSibling;
    text.nodeValue = text.nodeValue.replace('29-day free trial','');
});

JS Fiddle demo

删除第一个span后的所有内容:

$('.subscription-price').each(function(){
    var text = $(this).find('.amount')[0].nextSibling;
    text.parentNode.removeChild(text);
});

JS Fiddle demo

要隐藏它,你需要包装另一个元素,以便CSS能够定位这些词:

$('.subscription-price').html(function(i,h){
    return h.replace('29-day free trial', function(a){
        return '<span class="hideMe">' + a + '</span>';
    });
});

加上CSS:

span.hideMe {
    display: none;
}

JS Fiddle demo

或者,再次隐藏span后面的所有内容

$('.subscription-price').each(function(i,h){
    var text = $(this).find('span')[0].nextSibling;
    $(text).wrap('<span class="hideMe"></span>');
});

JS Fiddle demo

再次隐藏“29天......”部分,允许使用各种数字代替29

$('.subscription-price').html(function(i,h){
    return h.replace(/(\d{1,2}-.+)/, function(a){
        console.log(a);
        return '<span class="hideMe">' + a + '</span>';
    });
});

JS Fiddle demo

显然,要隐藏<{1}}元素之后的所有,最后一个代码块之前的jQuery代码段仍然有效,因为它不会根据数字隐藏,而是隐藏在DOM。

答案 1 :(得分:1)

使用replace()

var myStr = $('.subscription-price').text().replace(/ with a \d\d?-day free trial/g,'');

然后将其设置为文本,以便“隐藏”

$('.subscription-price').text(myStr);

所以现在你用''(空字符串)取代了'用XX天免费试用'。

答案 2 :(得分:1)

试试这个,

$(function(){
   var txt=$('.subscription-price').html().split('with ')[0];
   $('.subscription-price').html(txt);
});

小提琴 http://jsfiddle.net/p3vs6/

答案 3 :(得分:1)

如果文字始终保持不变,您可以使用:

var price_html = $(".subscription-price").html();
$(".subscription-price").html(price_html.replace(" with a 29-day free trial", ""));

以下是:JSFIDDLE

希望这有帮助!

答案 4 :(得分:0)

试试这个...

$('.subscription-price').each(function(){
var text = $(this).find('.amount')[0].nextSibling;
text.nodeValue = text.nodeValue.replace('/\s*month.*','');
});