Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the currency "Rs." occurring on multiple places 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

like image 386
Shalom Sam Avatar asked Jan 27 '26 18:01

Shalom Sam


1 Answers

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);
    });
});
like image 86
David Avatar answered Jan 29 '26 08:01

David