2013-07-03 40 views
0

我知道jQuery,但我在RegEx中有點小菜鳥。使用jQuery隱藏句子中的特定單詞

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

我想隱藏與這29天的免費試用(使用XX天免費試用版),則有可能使用jQuery正則表達式?或任何其他方法?

結果我想是提前

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

感謝, 阿賈伊

回答

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

要再次隱藏部分1929 -days ......「,允許各種數字被用來代替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

顯然,隱藏一切.amount元素jQuery的片斷之前的最後一個代碼塊,仍能正常工作下,因爲它不是基於數字隱藏,但其在DOM位置。

+0

什麼是29是什麼值?像19,25,10 –

+0

他們會永遠是數字,他們會一直是兩位數嗎?它是*僅僅是'29日......'的一部分,還是全部是'span'後面的文字? –

+0

永遠是否定的,它將是1-31 –

1

使用replace()

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

,然後將其設置爲文本,以便它 '隱藏'

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

所以現在你用''(空字符串)替換'XX天的免費試用'。

+0

不只是要隱藏。 –

+0

15美元/月,29天免費試用 - > 15美元/月 –

+0

您可以將新字符串設置爲文本,然後在您的範圍內更新我的答案 – AntouanK

1

試試這個,

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

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

1

如果文本停留在任何時候都一樣,你可以使用這個:

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

下面我們一起來看看:JSFIDDLE

H這有助於!

+0

如果天(29)是動態的呢? –

0

嘗試......

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