Extracting a targeted subsequence from a string in JavaScript

I have a dynamic string that is created in one of the following ways:

var q = "FROM Table SELECT sum(1), count(2), avg(3) where x='y'

var q = "SELECT min(1), max(2), average(3) FROM Table where z='x' since y days ago

The values after the select statement can vary from 1 to 10. I am trying to develop a method to always extract the selected values into an array, but I am struggling with the variable nature (the dynamically constructed string and the varying number of selects).

In essence, I want the final result to look like this:

['sum(1)', 'count(2)', 'avg(3)']

Currently, my approach involves the following code, but it relies on the string being organized in a specific way (always starting with SELECT and having a where clause after the fields to extract):

let splitQ = q.match(".*SELECT(.*)where");
let selects = splitQ[1].trim().split(",");

Answer №1

Below is a functional solution provided with certain assumptions about the query (in lowercase form).

  • The values are assumed to appear after the first occurrence of the word 'select.'
  • If the query begins with 'from,' the values are expected to end before encountering 'where.'
  • If the query starts with 'select,' the values should end before reaching 'from.'

const test1 = "FROM Table SELECT avg(1), avg(2), avg(3) where x='y'";

const test2 = "SELECT avg(1), avg(2), avg(3) FROM Table where z='x' since x days ago";



function extractValues(query) {
  // in both scenarios, the values always come directly after 'select '
  const valuesComeAfterMe = 'select ';
  query = query.toLowerCase();
  let valuesEndBeforeMe;
  // conditionally handle both query syntaxes
  if (query.startsWith('from')) {
    valuesEndBeforeMe = ' where';
  } else if (query.startsWith('select')) {
    valuesEndBeforeMe = ' from';
  } else {
    throw Error('query not handled');
  }
  // remove start
  query = query.slice(query.indexOf(valuesComeAfterMe) + valuesComeAfterMe.length);
  // remove end
  query = query.slice(0, query.indexOf(valuesEndBeforeMe));
  // split values and trim whitespace
  return query.split(',').map(item => item.trim());
}

console.log(extractValues(test1));
console.log(extractValues(test2));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Strategies for making a child div fade out when the parent div is hovered over

I have a div with the class name ordershape and inside it, there is another div called fad-res. My goal is to display the corresponding fad-res when I hover over a specific ordershape, while hiding the other divs. <div class="ordershape"> & ...

Printing array of API results in NodeJS using ExpressJS

I have been working with the Twitter API to retrieve tweets and store them in an array. I am looking to print the entire array on my HTML document for display purposes. Excited to see it work! Thanks! Check out the code snippet below: var express = requi ...

What's the best way to loop through each touch event property within the TouchList of a touch event using JavaScript?

I'm struggling to grasp touch events, as nothing seems to be working for me. For testing purposes, I've created a very basic page: HTML: <div id="TOUCHME"> TOUCH ME </div> <div id="OUTPUT"></div> Jav ...

Looking to find the length of a word within a txt file using jQuery?

I'm facing an issue with parsing text from a file. The file in question can be accessed via the following link: File: google-books-common-words.txt [1] Word => 'THE' USED => 53097401461 [2] Word => 'OF' USED => 3096 ...

What is the most efficient way to retrieve an image from a database using its unique ID while incorporating CSS

My database table consists of the following columns: ID Nome Country Imagem 1 John USA images/######.jpg 2 Ana USA images/######.jpg 3 ## ## images/######.jpg How should I begin my code? I am looking to retrieve the image based on the ...

Straightforward JSON issue

I am new to JSON and I need to work with it now. I have tried several examples from the jQuery page, but they don't seem to be working for me. I have a *.php file that generates a string. From what I understand, this is how I pass JSON data from PHP ...

Spring REST service prevents Cross-Origin Requests with AJAX

Having Trouble Accessing Spring REST Service My spring service @RequestMapping(value = "/MAS/authenticate", method = RequestMethod.POST) public ResponseEntity<Map<String, String>> authenticate(@RequestBody Subject subject) { Map<String ...

Ways to verify if the user has inputted a typeahed value

My code snippet looks like this: var students = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('fullName'), queryTokenizer: Bloodhound.tokenizers.whitespace, remote: { ...

What is the best method for testing an Angular service that has dependencies in Jasmine?

My service implementation is structured as follows: angular.module('app').service('MyService' , function (dependency1, dependency2, dependency3 ...) { function funcToTest() { // Do something } } I am wondering how I ca ...

Guide on navigating to a different page following a successful Google Sign In within React18

I'm facing an issue with redirection after signing in with Google on my React 18 project. Despite successfully logging in, the page does not redirect as expected. Below is a snippet of my Login.jsx file where the Google login functionality is implemen ...

GraphQL Error (Status Code: 429) - Next.js Development issue

If you're facing a GraphQL Error (Code: 429) while working on a nextjs project, here's a handy solution. Here's what happened: I created a headless CMS using Hygraph and NextJS 13 for a blog project. I also utilized the npm package graphql ...

Form containing a pair of buttons

I am attempting to design multiple forms with two buttons, each of which will submit the form to a different script. One button will use ajax for submission, while the other will simply submit the form without ajax. <?php foreach($objects as $object) : ...

The error message "reverseMessage is not a function" occurred in Vue.JS

I am attempting to show a string in reverse order using Vue. My template code is as follows: <div id="app"> <reverse :msgreverse="message" :reverseMessage="reverseMessage()"></reverse> </div> Here is my script: function reverse ...

Showcasing certain elements as the user scrolls

Looking for a way to display an element (such as a div) when the user scrolls without using JQuery? Here's an example that tries to achieve this: var scroll = document.body.scrollTop; var divLis = document.querySelectorAll("div"); for(let i = 0; i ...

Encountered a cyclic dependency in MongoDB when attempting to create an index

I have a dataset structured as shown in the image below: https://i.sstatic.net/eu2ZH.png I am attempting to write a query using $near. However, when trying to create an index for this query, I encounter an error stating "cyclic dependency detected". Below ...

The radio buttons are stuck and not changing their selection

Having a group of radio buttons with the same name, when one is checked, it automatically selects another one in the group. Here is my current code: <input name="a" type="radio"> <input name="a "type="radio" checked> JS $("input[type='r ...

Using a PHP variable to trigger the jQuery .show() function

I'm attempting to trigger jQuery .show() events based on PHP variables. Below is my PHP code (retrieved from a form submission on another page): $last_pic_displayed = trim($_POST["last_pic_displayed"]); if (strlen($last_pic_displayed) <= ...

Is there a pure JavaScript solution to replace jQuery's .prev() function?

Looking for a JavaScript alternative to this jQuery code: $(".q-block-container").prev(".sub-block-container").css("border-bottom","none"); I am seeking a pure JavaScript solution that selects the previous sibling ONLY if it matches a specific selector ( ...

Creating a standalone script using npm JS package for exporting

I'm currently utilizing the npm package manager in my latest project. Within my package.json file, I have a dependency specified: "dependencies": { "litepicker": "^2.0.11" }, The dependency is on litepicker, which i ...

Could you advise on the best placement for my upcoming JQuery animation?

Here is the code I am currently working with: $(function() { $("button").click(function() { $("#box1").animate({ left: $(window).width() - 800 }, { complete: function() { $("#box1").hide(); } }); $("#box2").a ...