Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement .indexof for an array of strings?

How can I simplify below code? How can I get rid of the if statements? I want to highlight some lines in ajax response. Right now I have two strings to compare = two ifs. This number will increase so I am thinking of doing this some other way - using an array of the strings that needs to be highlighted in case the string is part of data_array element.

I prefer a solution in javascript only but jQuery is ok too.

    data_array=data.split('<BR>');
    for(var i=0, len=data_array.length; i < len; i++){
        if (data_array[i].indexOf('Conflict discovered') >= 0){
            data_array[i]="<span class='red'>"+data_array[i]+"</span>";
        }   
        if (data_array[i].indexOf('Syntax error') >= 0){
            data_array[i]="<span class='red'>"+data_array[i]+"</span>";
        }   
    }
    data=data_array.join('<BR>');
like image 269
Radek Avatar asked Dec 19 '25 00:12

Radek


1 Answers

Add more elements to the array as desired :)

data.replace( /<br>/ig, '\n' ).replace(
    new RegExp( '^(.*(?:' + [
          'Conflict discovered'
        , 'Syntax error'
    ].join( '|' ) + ').*)$', 'gm' )
, '<span class="red">$1</span>' ).replace( /\n/g, '<br>' );

explanation:

  • replace <br> tags with line breaks
  • make a regexp: ^(.*(?:Conflict discovered|Syntax error).*)$
  • surround matches with <span class="red"> ... </span>
  • turn line breaks back in to <br> tags