Divide by value, but save the value in an array of results

I am trying to write a method that searches for elements matching a query, such as C # Linq.

So for example:

myObj.query("name == 'Bob' and age >= 18");

So, I thought it was best to start each group, so first I break up into andand or. It seems to give me half what I want.

So, I am doing this:

Object.prototype.query = function(string){
    console.log(string.split(/(?=(and|or))/g));
};

The problem is that I get the wrong output in the console:

0: "name == 'Bob' "
1: "and"
2: "and age >= 18"

I was looking for something similar (note 2, it no longer contains and):

0: "name == 'Bob'"
1: "and"
2: "age >= 18"

I think I'm going in the right direction, I'm just not that good with regex, so what should I do to split into two values, but keep them in the output?

+4
source share
2 answers

, lookahead. , , . /\s+(and|or)\s+/

"name == 'Bob' and age >= 18 and ornate=='lando'".split(/\s+(and|or)\s+/)

,

["name == 'Bob'", "and", "age >= 18", "and", "ornate=='lando'"]

"" , ( ) /\s+(and|or)\s+(?![\w\s]*')/

"name == 'Bob' and age >= 18 and ornate='me and lando'".split(/\s+(and|or)\s+(?![\w\s]*')/)

["name == 'Bob'", "and", "age >= 18", "and", "ornate='me and lando'"]
+4

Object.prototype.query = function(string){
    console.log(string.split(/\s+(and|or)\s+/g));
};

var myObj = {};
myObj.query("name == 'Bob' and age >= 18");

[ 'name == \'Bob\'', 'and', 'age >= 18' ]
+2

All Articles