str = " hello haizei "; function trim(s) { return s.replace(/(^\s*)|(\s*$)/g, ""); } ans = trim(str); console.log(ans);