JavaScript strip tabs function

kbjradmin

New Member
Messages
512
Reaction score
2
Points
0
ok, so i wrote a function to find all 'pre' tags with the class name 'code' and strip out the first n number of tabs from each line, then put the new text back in the 'pre' tag.

Code:
function untabCodePres(tabs)
{
    if ( ! tabs ) { var tabs = 5; }
    var codeBlocks = document.getElementsByTagName('pre');
    for ( var i in codeBlocks )
    {
        if ( codeBlocks[i].className == 'code' )
        {
            var text = codeBlocks[i].innerHTML.split("\n");
            for ( var line in text )
            {
                if ( text[line].substring(0,tabs-1) == "\t".repeat(tabs) )
                {
                    text[line] = text[line].substr(tabs);
                }
                if ( text[line] == '' )
                {
                    delete text[line];
                }
            }
            codeBlocks[i].innerHTML = text.join("\n");
        }
    }
}

but for some reason, it's not working. please help.

http://portfolio.kbjrweb.com/web.php?id=1 is an example, the dark box is the 'pre' tag.
Edit:
nevermind, i got it.
for some reason, it wasn't getting through
if ( text[line].substring(0,tabs-1) == "\t".repeat(tabs) )
structure.

anyway, it works now. :)
 
Last edited:

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
String.repeat isn't a standard method. One possible reason why the code wasn't working is that the script that defined String.repeat wasn't included with the page.

Another problem with the same line is that String.substring(i, j) doesn't include the character at the latter index j, so the line was comparing a string of length 'tabs-1' and another of length 'tabs'.

For what it's worth, here's a function that does the same thing using REs. To me, it's much clearer.
Code:
function untabCodePres(tabs) {
	if ( ! tabs ) {
        tabs = 5; 
    }
    var tabRE = new RegExp("^\\t{"+tabs+"}\\n?", "gm");
    var codeBlocks = document.getElementsByTagName('pre');
    for ( var i in codeBlocks ) {
        if ( /\bcode\b/.test(codeBlocks[i].className) ) {
            codeBlocks[i].innerHTML = codeBlocks[i].innerHTML.replace(tabRE, '');
        }
    }
}
Here's one that converts all leading tabs into spaces.
Code:
function untabifyPres(tabSize) {
    if ( ! tabSize ) {
        tabSize = 4; 
    }
    var spaces=" ".repeat(tabSize);
    var codeBlocks = document.getElementsByTagName('pre');
    for ( var i in codeBlocks ) {
        if ( /\bcode\b/.test(codeBlocks[i].className) ) {
            codeBlocks[i].innerHTML = codeBlocks[i].innerHTML.replace(/^\t+/gm, 
                                                  function(tabs) {return spaces.repeat(tabs.length);});
        }
    }
}

String.repeat brings an applicable algorithm to mind: have you seen Russian peasant multiplication?
 
Top