Javascript find text on page

前端 未结 5 546
广开言路
广开言路 2021-01-14 22:13

I need to run a search and replace on HTML similar to the following... I need to have \"Find Next\" \"Replace\" and \"Replace All\" options.... the trick is that I need to r

5条回答
  •  野的像风
    2021-01-14 22:43

    Here's a pure Javascript solution. You can store the innerHTML of #sheet to a global variable and then use the search input value in a new RegExp to replace the found text with whatever you want. So given the following HTML:

    This is yet another test
    This is test data

    You could do something like:

    var sheet,
        searchIt = function() {
            var v = document.getElementById('t').value;
    
            sheet = (typeof sheet == "undefined") ?
                    document.getElementById('sheet').innerHTML :
                    sheet;
    
            document.getElementById('sheet').innerHTML = 
                sheet.replace(new RegExp(v, 'ig'), "$&");
        };
    

    The $& in the replace represents the matched RegExp.

    See working example →

提交回复
热议问题