improved performance by changing string replace from recursive to loop