There is a string that looks like

Some text tag, tag, scope = some scope, scope2

It is necessary to break this text into a string and an array of the form {Key,Value} where Key is the value that goes before = , and Value is a comma separated list. That is, the result should be:

 queryText = "Some text" parameters = { [Key:tag; Value:Tag for this text], [Key:tag; Value:second tag], [Key:scope; Value:some scope], [Key:scope; Value:some scope2] } 

I did this:

 var query = queryString.val().trim().split(" "); var queryText = query[0]; if(query.length > 1) { var itm = 1; var currScope = ""; for(itm; itm < query.length; itm ++) { if(query[itm].indexOf("=") > -1) { var filterVal = query[itm].split("="); currScope = filterVal[0]; var keys = filterVal[1].split(","); for(var k in keys) { if(keys[k]) { this.parameters.push({ Key: currScope, Value: keys[k] }); } } } else { if(currScope) { this.parameters.push({ Key: currScope, Value: query[itm]}); } } } } 

But such an implementation only works if in the queryString all phrases without phrases, that is, one phrase, without spaces.

How to expand the implementation correctly?

  • key can't include spaces? - Grundy
  • can. I can’t break a string correctly to put phrases into an array. Fixed - LocalUser
  • one
    then I didn’t quite understand why the example in question "Some text" went to queryText , and not to [Key: Some text tag; - Grundy
  • because Some text is just text, and everything that comes after tag = should go to an array. tag is Key, as well as scope. in the sense of everything that goes after = should be written to an array, where Key should be the value that is before =. This values ​​will be without spaces, one phrase. - LocalUser
  • 2
    Maybe the next regular season will be - Grundy

1 answer 1

Did so.

 function parseQuery:(queryText, searchParameter){ var queryText = queries.split(" "); var newQuerytext= ''; for (var q in queryText) { if (queryText[q].indexOf("=") > -1) { break; } newQuerytext = newQuerytext + ' ' + queryText[q]; } var scopesArray = []; var rex = new RegExp("([" + searchParameter + "]+=[^=]+)(?![^\\s])", "g"); var matchArr = rex.exec(queryText); if(matchArr !== null && matchArr.length > 0) { var query = matchArr[0]; var vals = query.split("="); var values = vals[1].split(","); for(var v in values) { scopesArray.push({Key: searchParameter, Value: values[v]}); } } }