function foo(n, glue, str) { return str.length<n?str=Array(n+1).join(glue).replace(RegExp(".{"+str.length+"}$"),str):str; } alert(foo(4,0,"r")+"\n"+foo(4,0,"qwe"));