Javascript替换匹配值

时间:2017-10-04 10:45:55

标签: javascript regex lodash

我有这个字符串,我需要删除与值匹配的AND子句。例如:RHID = '540' AND SEQ LIKE '%44%' AND NR_DOCUMENTO LIKE '%999%'

如果值为'%999%'我需要删除AND NR_DOCUMENTO LIKE '%999%'。 如果值为'%44%'

,我需要删除AND SEQ LIKE '%44%'

注意:AND查询部分是动态的,可能有不同的东西,因此更像是找到值并向后移除到AND

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

AND(?=(?:(?!AND).)*'%(?:44|999)%').*?LIKE\s+'%.*?%'

Regex Demo

const regex = /AND(?=(?:(?!AND).)*'%(?:44|999)%').*?LIKE\s+'%.*?%'/gim;
const str = `'540' AND sEQ LIKE '%44%' AND NR_DOCUMENTO LIKE '%45%' AND bla bla bla LIKE '%999%'`;
const result = str.replace(regex,``);
console.log(result);

答案 1 :(得分:0)

这应该可以解决问题:

var string = "RHID = '540' AND SEQ LIKE '%44%' AND NR_DOCUMENTO LIKE '%999%'";

function replaceIt (valueSEQ, valueLIKE) {
  return string.replace(" AND SEQ LIKE '%" + valueSEQ +"%'", "")
               .replace(" AND NR_DOCUMENTO LIKE '%" + valueLIKE + "%'", "");
}

console.log( replaceIt(44, 999) );



    var string = "RHID = '540' AND SEQ LIKE '%44%' AND NR_DOCUMENTO LIKE '%999%'";
    
function replaceIt (valueSEQ, valueLIKE) {
    return string.replace(" AND SEQ LIKE '%" + valueSEQ +"%'", "")
                 .replace(" AND NR_DOCUMENTO LIKE '%" + valueLIKE + "%'", "");
}
    
console.log( replaceIt(44, 999) );