Search code examples
javascriptregexmarkup

RegExp - Replace some characters between <td> markups


I coded an AJAX function to make a search engine in a database. I want to highlight in yellow the searched characters in the displayed result.

The following code is working pretty well:

$.ajax({
    type: "GET",
    url: "search_db.php",
    data: "q="+valueSearch,
    dataType: "JSON",
    success: function(returnQuery) {
        $("#table tbody").empty();
        // console.log(returnQuery);
        $.each(returnQuery, function(i, line) {
            content = '<tr>';
            content += '<td>' + line.name_serv + '</td>';
            content += '<td>' + line.name_dns + '</td>';
            content += '<td>' + line.ip + '</td>';
            content += '<td>' + line.pass1 + '</td>';
            content += '<td>' + line.pass2 + '</td>';
            content += '</tr>';

            re = new RegExp('('+valueSearch+')', "gi")
            content2 = content.replace(re, '<span style="background-color: #ffff66;">$1</span>');

            $(content2).appendTo("#table tbody");
        });
    }, 
    error: function() {
        $("#table tbody").empty();
    }
});

There are three cases where it doesn't work properly: if I search 'd', 't' or 'r' (because the remplacements are made in the <td> or <tr> markups too).

Here is an example of the variable content:
"<tr><td>Jupiter</td><td>mail.test.com</td><td>10.0.0.1</td><td>root</td><td>a$01'deK</td></tr>"

I try to make a RegExp to add the <span> markup only to characters matching the search between <td> and </td>, but I don't find the right syntax.

Does anyone have an idea (pure JavaScript and/or jQuery)?


Solution

  • My advice would be to run the regular expression BEFORE embedding the lines into td's, and do it on each line individually. I would create a function inside of the ajax call like this:

    highlightMatches(line, valueSearch))
    {
    
    re = new RegExp('('+valueSearch+')', "gi")
    line2 = line.replace(re, '<span style="background-color: #ffff66;">$1</span>');
    
      return line2;
    }
    
    
    
    line.name_serv = highlightMatches(line.name_serv, valueSearch)
    line.name_dns  = highlightMatches(line.name_dns, valueSearch)
    .
    .
    .
    .

    THEN I'd wrap each of the lines into content just as you've done.

    That's my approach at least.