在字符串中进行棘手的多次替换

时间:2022-07-05 16:53:39

My string is something like

我的字符串是这样的

var query = "@id >= 4 OR @id2 < 6 AND @id3 >= 5 AND @name = foo "

Now what I would like to do with this string is to reverse every "equality" test. Replacing ' >=' by ' <' , ' <' by ' >=' and ' =' by ' !=' .

现在我想用这个字符串来反转每个“相等”测试。将'> ='替换为'<','<'by'> =','='替换为'!='。

The result I want :

我想要的结果:

var reverseQuery = "@id < 4 OR @id2 >= 6 AND @id3 < 5 AND @name != foo "

We can't use :

我们不能使用:

reverseQuery = query.replace(/>=/g, "<").replace(/</g, ">=").etc

Because the result of this would be

因为这样做的结果

@id >= 4 OR @id2 >= 6 AND @id3 >= 5 AND @name != foo 

Right ? So how to do this nicely ?

对 ?那么如何做得很好呢?

Thanks,

谢谢,

1 个解决方案

#1


6  

Use a single replace with a callback function that determines the replacement.

使用具有确定替换的回调函数的单个替换。

query = query.replace(/(<=?|>=?|=|<>|!=)/g, function(m){
  switch(m) {
    case '<': return '>=';
    case '>': return '<=';
    case '<=': return '>';
    case '>=':return '<';
    case '=': return '!=';
    case '<>': return '=';
    case '!=': return '=';
  }
});

Demo: http://jsfiddle.net/Guffa/s2xj5/

演示:http://jsfiddle.net/Guffa/s2xj5/

#1


6  

Use a single replace with a callback function that determines the replacement.

使用具有确定替换的回调函数的单个替换。

query = query.replace(/(<=?|>=?|=|<>|!=)/g, function(m){
  switch(m) {
    case '<': return '>=';
    case '>': return '<=';
    case '<=': return '>';
    case '>=':return '<';
    case '=': return '!=';
    case '<>': return '=';
    case '!=': return '=';
  }
});

Demo: http://jsfiddle.net/Guffa/s2xj5/

演示:http://jsfiddle.net/Guffa/s2xj5/