function clearlog(){
document.getElementById('logtarget').innerHTML='';
}
function log(s){
document.getElementById('logtarget').innerHTML+='\n---\n'+s;
console.log.apply(console, arguments);
}
var ta = document.getElementById('ta');
ta.addEventListener("keyup", function(e){
clearlog();
test(ta.value);
}, false);
function unindentOrFalse(str) {
var lines,line,valid = false,crlf;
str = ''+str;
crlf = str.match(/\r\n/);
lines = str.split(/\r?\n/);
for(var i=0;i<lines.length;i++){
line = lines[i];
if(line.trim() === ''){
// skip empty lines
continue;
}
if(line[0]!=='\t'){
return false;
}
lines[i]=line.substr(1);
valid = true;
}
if(!valid){
// nothing was replaced (i.e. only empty lines?)
return false;
}
return lines.join(crlf?'\r\n':'\n');
}
function unindentAsFarAsPossible(str) {
var newstr;
while(newstr = unindentOrFalse(str)){
str = newstr;
}
return str;
}
function cleanupWhitespace(str) {
// remove end of line whitespace, normalize all newlines to \n, and remove empty lines (by replacing double newlines with nothing in between)
str = str.replace(/(\s*\r?\n)+/g,'\n');
// remove all whitespace up to and including first newline found from start of string if there are no non-whitespace characters in it (first line(s) only).
str = str.replace(/^\s*\r?\n/,'');
// remove all whitespace up to and including first newline found from end of string if there are no non-whitespace characters in it (last line(s) only).
str = str.replace(/\r?\n\s*$/,'');
// now try to remove indent tabs from all lines while we still can on each (nonempty) line:
str = unindentAsFarAsPossible(str);
return str;
}
function test(s){
var s2=unindentAsFarAsPossible(s);
var s3=cleanupWhitespace(s);
log(s);
log(s2);
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.