jonkratz
jonkratz

Reputation: 123

Iterate through a string and add tags using javascript

I'm working on a website project and I have a paragraph containing a list of items (it would work great as a ul, but needs to stay a p) that needs to have the first letter of each item bold. I've created a function to do this:

function inserter(string, splitter, skip) {
    var array = string.split(splitter);
    var len = array.length;

    for(var i = 1; i < len; i++) {
        var a = array[i];
        var b = '<b>';
        var c = '</b>';
        if(a.substr(0, 3) != skip){ 
            array[i] = splitter + b + a.substr(0,1) + c + a.substr(1);
        } else { 
            array[i] = splitter + a; 
        }
    }
    var strFix = array.join("");
    return strFix;
}

$(function(){
    var text = $(".caps").html();
    text = inserter(text, ': '); //bold the item after ': '
    text = inserter(text, ', ', 'and'); // now bold after the comma ', ' and the skip variable which matches first three letters so the last and doesn't get bold
    text = inserter(text, ', and '); //now for the item after the last 'and'
    $(".caps").html(text);
});

But it needs to be called and the string iterated for every different splitter (which could ruin performance on pages with more than a few of these), and I'm wondering how I could just call it once so all the splitters are looked at during one iteration?

Example page:

http://heidikratzke.com/about.php

When you see the page, you will see that I will be doing this on multiple paragraphs within a jQuery slideshow.

If it doesn't seem like this will be a performance hit for slower browsers, I'll leave it as is.

Appreciate any suggestions on how to do it better.

Upvotes: 1

Views: 1247

Answers (1)

Robusto
Robusto

Reputation: 31883

One optimization you could make is to use the splitter you use to split the string into an array to join the array once the operation is finished:

function inserter(string, splitter, skip) {
    var array = string.split(splitter);
    var len = array.length;

    for(var i = 1; i < len; i++) {
        var a = array[i];
        var b = '<b>';
        var c = '</b>';
        if(a.substr(0, 3) != skip){ 
            array[i] = b + a.substr(0,1) + c + a.substr(1);
        } else { 
            array[i] = a; 
        }
    }
    return array.join(splitter);

}

There's probably more you could do here as well, but this jumped out at me.

further optimization

The following gets variable declaration out of the loop:

function inserter(string, splitter, skip) {
    var array = string.split(splitter);
    var len = array.length;
    var i, a, b='<b>', c='</b>';

    for(i = 1; i < len; i++) {
        a = array[i];
        if(a.substr(0, 3) != skip){ 
            array[i] = b + a.substr(0,1) + c + a.substr(1);
        } else { 
            array[i] = a; 
        }
    }

    return array.join(splitter);    
}

Upvotes: 2

Related Questions