0

I'm trying to parse WHERE clause of mysql query into an expression to get data from json file

For example:

`price`=8.95 AND `title`="The Lord price= AND of the Rings"

above example should be converted to the below string after replacing price and title value on left hand side

8.95==8.95 && 'The Lord price= AND of the Rings'=="The Lord price= AND of the Rings"

I have created one code (jsfiddle) to achieve this but this will break if I add AND ` in value as show below (it returns false if condition is not matching)

var obj = {price: 8.95, title: "'The Lord price= AND `of the Rings'"};
var whereString = '`price`=8.95 AND `title`="The Lord price= AND `of the Rings"';

So I wanted to understand is there any other better way to achieve this?

2 Answers 2

1

In first step split your whereString with regex pattern

/(`[^`]+`=(?:"[^"]+"|\S+))(?:\s+AND\s+|$)/g

and store all Group 1 matches.

In second step do substitutions for each match and finally merge all matches with string AND

Sign up to request clarification or add additional context in comments.

Comments

1

Slightly different approach, indifferent to the form the quoted string takes; split by AND outside of quotes, replace and join:

let source = '`price`=8.95 AND `title`="The Lord price= AND of the Rings"';
let result = source
    .split(/\s*\bAND\b\s*(?![^`"]+")/)
    .map(s => s.replace(/`\w+`=(.*)/, '$1==$1'))
    .join(' && ');

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.