str = str.replace(/\'/g, "&"+"#39");

oppure:

var apice = "&" + "#039";
str = str.replace(/\'/g, apice);