开发者

Wrap every occurrence of the text "Rs." with <span class="someClass">

I have the currency "Rs." occurring on multiple places开发者_StackOverflow社区 on my site. I want to wrap every occurrence of the text with <span class="WebRupee">. But if it is already wrapped with <span class="WebRupee"> it should be ignored.

I cannot use $('*:contains("Rs.")').wrap("<span class=\"WebRupee\"); because this wraps the html around the node that contains Rs. but not around the text alone. And for the same reason I cannot use .wrapInner();

Again any help will be greatly appreciated!

EDIT : the javascript provided on the webrupee site doesn't work on my site(no clue why). So that's out of the question as a solution. And hence I thought of writing a custom javascript. Just don't know how I could approach this.

EDIT(2): thinking out loud - hmm is there a way to add html at the indexOf("Rs.") ..or a simmilar approach


First, what you are trying to do is a dirty hack.

You should fix it in the source, whatever it is (for example PHP backend, Ruby backend, plain HTML, etc...).

See this example working at http://jsfiddle.net/8jXLw/

I did many assumptions and simplifications, your Regular Expressions should be more complete.

var spanit = function(item) {
    var $item = jQuery(item);
    var regexp = /\d+ Rs\./;
    var text = $item.text();
    if (!regexp.test(text)) {
        return;
    }
    if ($item.has(".WebRupee").length) {
        return;
    }
    var new_text = text.replace(" Rs."," <span class='WebRupee'>Rs.</span>");
    $item.html(new_text);
};

jQuery(function() {
    $("p.test").each(function() {
        spanit(this);
    });
});


Use http://cdn.webrupee.com/js file. it is working fine. i had used for one website. If you want download and customize little.. thanks..


very inefficient solution

    var replaced = $("body").html().replace('Rs.','<span class="WebRupee">Rs.</span>');
    $('body').html(replaced);
    var replaced = $("body").html().replace('<span class="WebRupee"><span class="WebRupee">Rs.</span></span>','<span class="WebRupee">Rs.</span>');
    $('body').html(replaced);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜