JavaScript Regex Test and Replace



我需要清理一些字符。 我有一个有效的解决方案,但我想知道是否有更好的解决方案可能更快或更好,或者我是否应该以不同的方式解决这个问题?

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

反之亦然:

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;
}
您可以将

这些字符与单个字符类正则表达式/['"%]/g匹配,并在回调中将每个匹配项替换为相应的替换:

function myQuoteStr(_str) { 
  return _str.replace(/["'%]/g, function($0) { 
    return $0 === '"' ? "%22" : $0 === "'" ? "%27" : "%25";
  });
}
console.log(myQuoteStr(""-'-%"));
function myUnQuoteStr(_str) { 
  return _str.replace(/%2[257](?!d)/g, function($0) { 
    return $0 === '%22' ? '"' : $0 === "%27" ? "'" : "%";
  });
}
console.log(myUnQuoteStr("%22-%27-%25"));

请注意,在 myUnQuoteStr 中,/%2[257](?!d)/g 模式包含一个负的展望,以确保我们%255字符串中的%25不匹配。

中使用String.prototype.replace()函数就足够了。此外,无需转义%字符:

function escapeStr(_str){    
  _str = _str.replace(/%/g, "%25").replace(/"/g, "%22").replace(/'/g, "%27");
  return _str;
}
function unescapeStr(_str){
  _str = _str.replace(/%22/g, '"').replace(/%27/g, "'").replace(/%25/g, "%");
  return _str;
}
console.log(escapeStr('sdfsdf%%%""""''));
console.log(unescapeStr('sdfsdf%25%25%25%22%22%22%22%27'));

最新更新