One thing I needed to do recently was indent a series of strings with a variable number of tabs or spaces. Thusly, I decided to create the following function which can be used by anyone that would need such a function:


/**
 * Indents the given string
 * @param {string} str  The string to be indented.
 * @param {number} numOfIndents  The amount of indentations to place at the
 *     beginning of each line of the string.
 * @param {number=} opt_spacesPerIndent  Optional.  If specified, this should be
 *     the number of spaces to be used for each tab that would ordinarily be
 *     used to indent the text.  These amount of spaces will also be used to
 *     replace any tab characters that already exist within the string.
 * @return {string}  The new string with each line beginning with the desired
 *     amount of indentation.
 */
function indent(str, numOfIndents, opt_spacesPerIndent) {
  str = str.replace(/^(?=.)/gm, new Array(numOfIndents + 1).join('\t'));
  numOfIndents = new Array(opt_spacesPerIndent + 1 || 0).join(' '); // re-use
  return opt_spacesPerIndent
    ? str.replace(/^\t+/g, function(tabs) {
        return tabs.replace(/./g, numOfIndents);
    })
    : str;
}

The JS annotation pretty much sums up how you can use this function. Here is an example of using this function:


var msg = indent("Hello\nWorld!!!", 1);
alert('My message to you is:\n' + msg);
/* OUTPUT:
My message to you is:
    Hello
    world!!!
*/

Due to the fact that each computer may render a tab character differently, I have provided the ability to specify how many spaces to use in an indentation. This not only uses that many spaces for each of the indentations but also replaces all of the tab characters at the beginning of a line with that many spaces if any previously existed:


var msg = indent('Hello\n\tworld', 2, 6);
alert('My message to you is:\n' + msg);
/* OUTPUT:
My message to you is:
            Hello
                  world!!!
*/

Have fun indenting! 😎

Categories: BlogJavaScriptJScript

Leave a Reply

Your email address will not be published. Required fields are marked *