Is it possible to have a variable either inside quotation marks or NULL when checking for case within a string in JavaScript

The challenge lies in titling this particular question, but demonstrating it is quite straightforward. My goal is to include multiple value sets in an SQL insert statement like the following:

var sqlInsertString = `INSERT INTO events (url) VALUES`
var sqlInsertValuesString = `('${event.url ? event.url : null}', null, 1, 2, 3)`

pg_client.query(sqlInsertString + sqlInsertValuesString)

This process occurs within a loop, hence the need for separating the insert string and values string. What I aim for is to have the URL inserted as 'https://www.example.com' with quotes if event.url contains a URL, and to insert null if event.url is empty.

In my current code snippet above, 'null' is inserted as a string with quotes instead of an actual null value in the database. Removing the quotes would lead to errors due to the presence of ':' in the URL.

How can I modify the sqlInsertValuesString to either provide a valid URL string or a genuine null without quotation marks using this approach?

Answer №1

Using parametrised queries serves multiple purposes, not just for preventing injection attacks. It streamlines the process like this:

pg_client.query(
  "INSERT INTO events (url, nothing, one, two, three) VALUES ($1, $2, $3, $4, $5)",
  [event.url || null, null, 1, 2, 3]
)
.then(res => ...)
.catch(err => ...)

No need to worry about quoting, all the technicalities are taken care of by the driver.

Even if security isn't your primary concern, utilizing parametrised queries is beneficial for clarity and as a best practice: by consistently implementing parametrised queries always, you eliminate the risk of overlooking possible injections and inadvertently creating vulnerabilities in your program.

Answer №2

If you prefer not to use backticks, you have the option to do it differently

var event = {};
event.url = 'http://someurl.com';
var sqlInsertString = "INSERT INTO events (url, a, b, c, d) VALUES ";
var sqlInsertValuesString = "('" + (event.url ? event.url + "'" : null) + ", null, 1, 2, 3)";

console.log(sqlInsertString + sqlInsertValuesString);

var event = {};
var sqlInsertString = "INSERT INTO events (url, a, b, c, d) VALUES ";
var sqlInsertValuesString = "(" + (event.url ? "'" + event.url + "'" : null) + ", null, 1, 2, 3)";

console.log(sqlInsertString + sqlInsertValuesString);

Answer №3

To enhance clarity, it would be beneficial to break down the assignment into two steps:

let eventUrl = event.url ?? null;
const sqlInsertString = `INSERT INTO events (url) VALUES (${eventUrl}, null, 1, 2, 3)`

The nullish coalescing operator was utilized for assigning a value to eventUrl.

Answer №4

If you give it a shot

`(${event.url ? `'${event.url}'` : `null`})`

There will be single quotes enclosing the URL if it's present, but not for null values.

Answer №5

In my search on Google, I also discovered that using backslashes to escape the backtick can be effective:

${event.url ? (`\`` + event.url + `\``) : null},

However, after careful consideration, I found the selected response to be superior.

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

Utilizing SCSS to implement custom animations according to specific element IDs

How can I add different animations based on the ID of two DIVs with the same class when clicked? JSX: <div className="card"> <div id="front" className={frontClasses.join(' ')} onClick={clickedFront}> OPEN ...

What could be causing my canvas element to only display a blank black screen?

Setting up a 3d asset viewer in Three.js can be quite challenging, especially for someone who is new to JavaScript like myself. After following the advice to wrap my code within an 'init();' function, I encountered a new issue - a black screen in ...

The expansion animation for the Nextjs/React accordion box did not work as expected when utilizing tailwindcss

I am currently working on creating an animation for a collapsible box (accordion). My goal is to have the child component initially hidden with display:none. When I hover over the parent component, the child should be revealed and the dimensions of the pa ...

Allow the button to be clicked only when both options from the 1/3 + 1/3 radio buttons are selected

How can I ensure that the next <button> at the bottom of the HTML is only clickable when at least one of each <input type="radio"> is checked? Also, how do I integrate this with my current function? The button itself triggers a jQuery function ...

Regular expression that prohibits the acceptance of numbers with leading zeros

Below is the directive I am using to ensure that the input consists purely of numbers from 0-9. import { Directive, HostListener, ElementRef } from "@angular/core"; @Directive({ selector: "[numbersOnly]", }) export class OnlynumberDi ...

What is the method for identifying which input field the user has chosen on a web page retrieved from a server?

I attempted the code below without achieving the desired outcome. Any assistance would be greatly appreciated. UIPasteboard *pb = [UIPasteboard generalPasteboard]; [pb setString:passwordName]; NSString *jScriptString; jScriptString = [NSString string ...

A beginner's guide to integrating Socket.io with Express.JS using the Express application generator

Currently, I am attempting to utilize Socket.io alongside Express.JS by using the Express application generator. While searching for solutions, I came across some helpful advice on how to achieve this (check out Using socket.io in Express 4 and express-gen ...

Applying REGEX on input text in React Native

I'm having trouble getting my regex function to work correctly, so I believe there might be an error in my code. Any assistance would be greatly appreciated. Here is the regex function I am using: let validatePlate = (plate) => { var re = /(^[A ...

SQL: Aggregating dates by selecting one date from each month

Is there a way to group sales data based on a specific date? The date should be determined by when the sales data is exported. For example, if the data is exported on 2016/11/10, then the sales dates should be grouped accordingly. I attempted to use the d ...

I used npm to install AngularJS and then included AngularJS in my application

My goal is to set up AngularJS v1.5.x using npm and integrate it into my application for seamless utilization. Most tutorials opt for downloading the Angular Version from angularjs.org and manually adding it to the index.html within a <script></sc ...

Encountering a "Parsing error: Unexpected token, expected ";" " when developing a React application with the provided code

I am currently working on developing a React application, and I have encountered an issue in my app.js file regarding the render function. Despite being new to JavaScript, I am unable to figure out why this error is occurring. Apologies if it is due to a s ...

What is the best way to add data to a URL in an ActionResult Method using window.location.href?

I am having trouble understanding how to retrieve data using window.location.href = '/Product/Success/'+data.OrderTrackNo+'';. I am able to get data using ajax, but it seems different when retrieving data with window.location.href, whic ...

Maintain the state of the toggle div after page refresh or modification

In this scenario, I am looking to ensure that my div remains open even if the page is changed or refreshed. Below is the HTML and JavaScript code provided: You can view the working code here: http://jsfiddle.net/wasimkazi/fauNg/1/ $(".widget2").hide( ...

What causes the axios Library to fail in initiating a request if the API call does not begin with "https://"?

This issue has been resolved, but I still want to ask it in order to gain a better understanding of the underlying processes. So, I am using an API to retrieve data on the current weather in a specific city. The API call (as per the provider's documen ...

A comprehensive method in JavaScript to determine if a variable is defined

There was a moment when I recall stumbling upon a code snippet that utilized a javascript library, possibly lodash, to perform a comprehensive check for the existence of a certain element. For instance: someLib.isDefined(anObject.aNestedObject.anotherNes ...

Retrieve items by name using an HTML array

I am dynamically adding new inputs and would like to read values from them dynamically as well. However, I am facing an issue where my championName variable is not working in JavaScript. <form name="second_form" id="second_form" action="#" method="PO ...

Performing calculations on multiple rows of data in SQL Server using aggregate functions without the need for grouping

I have a complex script that extracts data from multiple tables and allows me to manipulate the data as needed. This script is intricate and highly sensitive - any grouping error could result in missing important data. Is there a way to utilize these funct ...

Trouble arises when attempting to create a two-column layout using Material UI's <Grid> component

My goal is to create a two-column layout where each column takes up half of the screen and has equal height. To better illustrate, take a look at this image. The code I've tried so far is not working as expected: import React from "react"; import { ...

Is it possible to send an email with an attachment that was generated as a blob within the browser?

Is there a way to attach a file created in the browser as a blob to an email, similar to embedding its direct path in the url for a local file? The file is generated as part of some javascript code that I am running. Thank you in advance! ...

Developing custom events in an NPM package

Developing a basic npm package with signalr integration has been my recent project. Here's how it works: First, the user installs the package Then, the package establishes a connection using signalr At a certain point, the server triggers a function ...