I’m toying around with handling pasted code in a textarea and wanted to left trim what is pasted up to the first non-spacing character. I want to take the following code:
if (foo)
{
console.log(bar);
}
And present it like so:
if (foo)
{
console.log(bar);
}
I’ve written code that breaks the text up so that I have each line in an array, then I iterate through that array, store the least amount of spaces in a variable, then iterate through the array again, using substr() to return the string after X characters. If any line has no leading space or tab, then no trimming should occur. What I have works (haven’t added support for tabs yet), but I believe there is a better way to do this. I’ve got a working sample on jsFiddle.
So… anyone know how I can accomplish this more efficiently?
This iterates through an array consisting of the spaces at the begning of each line. The iteration is done using jQuery’s map, but it could be done in two lines pretty easily with a loop if you prefer. It uses Math.min to find the smallest number of spaces in that array. Then it just replaces exactly that may spaces from the beginning of every line with the empty string:
Updated Fiddle
And another for fun
As for tabs, you’ll have to make a decision on how many spaces you consider a tab to be. Probably 4 or 5 would be a good choice. Then you can replace all tabs at the start of every line with that many spaces before reusing the same logic for spaces.