Search code examples
javascriptjqueryselecthighlight

What is a wrap method to wrap only a part of a string?


I have an HTML like this:

<div>
     <h3>How are you? Fine?</h3>
</div>

I would like to turn that in something different, using two numbers n and m, something like: if n=5 and m=12

<div>
     <h3>How 
            <span class="yellow">are you?</span>
      Fine?</h3>
</div>

In other words I would like to "highlight" only a part of a string using two numbers that specifies the start and the end of the "highlight" (in characters).

I tried this but it didn't work:

//in the previous example it will be a xpath selector for div/h3
var selection=$(document.body).xpath(selector).text();

//it will be "are you?"
var substring=selection.substring(n,m);

//it would make that i want, but it doesn't
                                $(document.body).xpath(selector).contents().filter(function() {
                        return substring;
                    }).wrap("<span class=\"yellow\"></span>");
}

Solution

  • One way to do it would be - instead of wrap, replace the content of the h3 with the slice up manipulated version.

    See this JSFiddle http://jsfiddle.net/9LeL3f3n/21/

    <div>
        <h3>How are you? Fine?</h3>
    </div>
    
    
    $(document).ready(function() {
    
        var highlight = function(str, start, end) {
          return str.slice(0,start-1) + 
            '<span style="color:#ffff00">' + 
            str.substring(start-1, end) + 
            '</span>' +  
            str.slice(-1 * (str.length - end));
        };
    
        var n = 5;
        var m = 12;
    
        $('h3').html(highlight($('h3').html(),n,m)); 
    
    });