3

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>');
3
  • @Ibu, You're why we can't have nice things. Commented Oct 16, 2012 at 1:29
  • 3
    @Ibu javascript = browser. jQuery = 32KB Commented Oct 16, 2012 at 1:29
  • @ibu - jquery != javascript. "but jQuery is ok too" implies solutions utilizing jQuery methods are acceptable Commented Oct 16, 2012 at 1:30

5 Answers 5

3

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
Sign up to request clarification or add additional context in comments.

15 Comments

Will this span the text from an array or the whole lot between <br>'s?
Yes, it was desired. :-) But I couldn't figure it out from the code by myself. So I asked.
yeah, that's what the ^(.* ... .*)$ is for, to match the whole line
Why did you have to replace <br> with new lines? I guess I can replace ['Conflict discovered' ] with a variable name, can't I.
because the ^ and $ match against beginning and end of lines. Without it, I'd need to overly complicate the regex to find entire lines between <br> tags. Yes, you can replace the [ ... ] with a variable. And yes, it's "one line" if that matters
|
3

Why not add another for loop?

data_array=data.split('<BR>');

var stringsToFind = ['Conflict discovered', 'Syntax error'];

for (var i = 0; i < data_array.length; i++) {

    for (var j = 0; j < stringsToFind.length; j++) {

        var currItem = data_array[i];

        if (currItem.indexOf(stringsToFind[j]) >= 0) {

            data_array[i]='<span class="red">' + currItem + '</span>';
        }
    }  
}

data = data_array.join('<BR>');

jQuery (note, may be slower, and I haven't tested this yet)

data_array=data.split('<BR>');

var stringsToFind = ['Conflict discovered', 'Syntax error'];

$.each(data_array, function(i, item) {
    $.each(stringsToFind, function(j, s) {
        if (item.indexOf(s) >= 0) {
            data_array[i]='<span class="red">' + item + '</span>';
        }
    }
});

data = data_array.join('<BR>');

6 Comments

In addition to that, I would use jQuery.each which is a nicer form of iteration.
@Anderson Silva: True, but this would be the pure javascript solution if Radek doesn't want the jQuery library.
Could you add sample of .each to you answer so I'll accept it?
@Radek Check my answer which doesn't use any loops
Yes, but I like yours the best. Sorry @Laurence.
|
2
var data_array = data.split('<BR>');
var errMsgs = ['Conflict discovered', 'Syntax error'];
data_array = data_array.map(function(data_rec) {
    var isAnError = errMsgs.some(function (errMsg) {
        return data_rec.indexOf(errMsg) >= 0;
    });
    if (isAnError) {
        return "<span class='red'>" + data_rec + '</span>';
    } else {
        return data_rec;
    }
});

3 Comments

+1 I didn't even know about some. This is a really good solution, @Insidi0us
some() is pretty new, see here for a JS equivalent: developer.mozilla.org/en-US/docs/JavaScript/Reference/…
Oh, but you should note that this is IE9 and all modern browsers only, according to developer.mozilla.org/en-US/docs/JavaScript/Reference/…
1

jsBin demo

var highlightWords = ['Conflict discovered', 'Syntax error', 'Simply cool'];

for(i=0; i<highlightWords.length; i++){
  var regex = new RegExp(highlightWords[i],'ig');
  data= data.replace( regex, '<span class="red">'+ highlightWords[i] +'</span>');
}

$('div').html( data );


jsBin demo 2 all line highlight

var words = ['Conflict discovered', 'Syntax error', 'Strange'];
var data_array=data.split('<BR>');

for(n=0;n<words.length;n++){
  for(i=0; i<data_array.length; i++){
      if (data_array[i].indexOf( words[n] ) >= 0){
           data_array[i]="<span class='red'>"+data_array[i]+"</span>";
      }   
  }
  data = data_array.join('<BR>');
}

$('div').html( data );

3 Comments

Your code highlights the (error) string only. Mine the whole line defined from <br> to <br>. I like it though. I learnt something new.
I like your solution very much too. Actually it is probably easier to read than @cwolves' one.
@Radek Thanks! I'm glad was helpful!
0
data_array=data.split('<BR>');
for(var i=0, len=data_array.length; i < len; i++){
    var dai = data_array[i];
    if (dai.indexOf('Conflict discovered') >= 0 || dai.indexOf('Syntax error') >= 0){
        data_array[i] = "<span class='red'>"+dai+"</span>";
    }   
}
data=data_array.join('<BR>');

2 Comments

Yes :-) but wouldn't be easier to have an array that I modify instead of introducing new if or or? I have one config file that I would like such array to have in.
@Radek, check out .map and .forEach

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.