JavaScript Regex Test and Replace I need to sanitize some chars.  I have a solution that works but I am wondering if there is a better solution that may be faster or better or if I flat out should be approaching this differently?

function escapeStr(_str){
    if (/\"|\'|\%/g.test(_str)) {
        _str = _str.replace(/"/g, "%22");
        _str = _str.replace(/'/g, "%27");
        _str = _str.replace(/%/g, "%25");
    }
    return _str;
}


And vice versa:

function unescapeStr(_str){
    if (/\%22|\%27|\%25/g.test(_str)) {
        _str = _str.replace(/\%22/g, '"');
        _str = _str.replace(/\%27/g, "'");
        _str = _str.replace(/\%25/g, "%");
    }
    return _str;
}
Instead of hardcoding the characters, and their escape values specifically in your .replace call, you can pass a callback function for the replacement. I suggested that you dive into encodeURI:

So, something like:



function escapeStr(_str) {
  return _str.replace(/([%'"])/g, encodeURI)
}

function unescapeStr(_str) {
  return _str.replace(/(%(?:2[257]))/g, decodeURI)
}
const e = escapeStr, u = unescapeStr;
console.log( e("string") );
console.log( e("some\" char%s") );
console.log( u("string") );
console.log( u("some%22 char%25s") );