JavaScript正则表达式测试和替换

时间:2017-01-27 21:52:39

标签: javascript regex

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

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;
}

2 个答案:

答案 0 :(得分:1)

您可以将这些字符与单个字符类正则表达式/['"%]/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模式包含一个负向前瞻,以确保我们与%25字符串中的%255不匹配。

答案 1 :(得分:0)

中使用String.prototype.replace()功能就足够了。此外,无需转义% char:



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'));