In JavaScript, use regex to replace specific characters while excluding a particular set

const sqlQuery = 'select * from where item1=abcd and price>=20';

To replace the '=' with empty space, I am using the following code:

sqlQuery = sqlQuery.replace(/[=]/g, " ")

However, this code is also replacing '>='. I want to keep expressions like '>=', '==' or '<=' untouched.

Therefore, the desired output should be -

'select * from where item abcd and price>=20'

I appreciate any assistance in achieving this goal.

Answer №1

Here is a regex pattern you can use for replacement:

/([a-z0-9]+)\s*=\s*([a-z0-9]+)/gi

You can replace it with $1 $2.

  1. ([a-z0-9]+): This matches one or more alphanumeric characters and captures them in a group.
  2. \s*: Represents zero or more space characters.
  3. =: Signifies an equal sign.
  4. gi: Flags used in the regex - g for global (matches all occurrences) and i for case-insensitive matching.

The replacement part uses $n to refer to the captured groups from the regex match.

let regex = /([a-z0-9]+)\s*=\s*([a-z0-9]+)/gi;
let str = 'select * from where item1=abcd and price>=20';

console.log(str.replace(regex, '$1 $2'));

Answer №2

Substitute a specific symbol for a letter or number on each side with the corresponding characters separated by a space.

str.replace(/([a-zA-Z0-9])=([a-zA-Z0-9])/, '$1 $2')

When using regex, [] signifies "the set of", therefore [a-zA-Z0-9] represents one character that can be any lowercase letter, uppercase letter, or digit.

Answer №3

A quick and easy hack. Just take out the letter g from variable regx

let phrase = 'find all items greater than or equal to 20 in quantity';
console.log(phrase.replace(/[=]/, " "))

Answer №4

One effective strategy for tackling these issues is to selectively identify everything you want to skip over, and then specifically exclude anything you want to eliminate. For instance:

(>=|<=|==|'[^']*(?:''[^']*)*')|=

after which you can substitute it with $1.

For a practical demonstration: https://regex101.com/r/3pT9ib/3

  • To begin, we establish a capturing group: (...), which is stored in $1.
    • This group matches >= and <=. I even included == (although I'm not sure if that's SQL), as well as escaped SQL strings, just to illustrate.
  • If the group was unable to be matched, we can reliably find and remove any remaining =.

This methodology is nicely outlined here: Regex Pattern to Match, Excluding when... / Except between

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

Problem encountered when attempting to post to a node/express endpoint

It has been a while since I last used JQuery/Ajax instead of axios to connect to an endpoint, am i making any mistakes here? var express = require('express'); var app = express() var bodyParser = require('body-parser'); var path = re ...

javascript primary inquiry

When a page contains an iframe within an iframe, is it necessary to use parent.parent to access the top frame? Is there a quicker way to navigate to the root of the page instead of using parent.parent; or even parent.parent.parent? ...

Does anyone have any insight on why I can't seem to remove an item from my list of tasks?

Having trouble with my React todo list. After submitting, the list item looks fine. I expect to be able to delete it by clicking on the item, but nothing happens. When I try to add another item, the page refreshes and all items are removed. The console ...

What is the simplest method for moving cells between two tables using drag and drop?

Is there a way to select random cells from a table and move them to another table using drag and drop functionality? I'm looking for a library that can help achieve this with JavaScript and PHP. Additionally, I need to save the ID of the selected cel ...

Canvas not displaying image in JavaScript

I have a bird object with a draw function defined, but for some reason, the image is not showing up when called in the render function. Can someone please help me figure out what I'm doing wrong? Thanks in advance. EDIT: Upon further investigation, I ...

Dynamic Button with Jquery and CSS Grid

I have a div that includes a heading using and a Vertical Navigation menu in the same container. To ensure responsiveness, I utilized media queries along with "Display:none and position:abolute" for the Navigation Container, which worked flawlessly up to ...

Sharing details of html elements using ng-click (AngularJS)

I am currently exploring options to enable users to click on a "open in new tab" link, which would essentially transfer that HTML element into a fresh window for their convenience. I am seeking advice on how to achieve this. At the moment, I am able to la ...

I often find myself frustrated while using Next.js because the console automatically clears itself, making it difficult for me

I am facing an issue with my form in the Next.js app. Here is how it is defined: <form onSubmit = { async() => await getCertificate(id) .then(resp => resp.json()) .then(data => console.log(data)) }> Whenever there is an erro ...

Using Mocha with the --watch flag enabled causes issues with ES6 modules and results in error messages

I've been attempting to configure Mocha to automatically monitor for changes in my files using the --watch flag. I have defined two scripts in package.json as follows: "test": "mocha", "test:watch": "mocha --watch ./test ./game_logic" When I run ...

Tips for updating a single attribute in Mongoose

I am currently using mongoose version 4.1.8 and below is an example of my mongo db schema: (function() { 'use strict'; const mongoose = require('mongoose'); const Schema = mongoose.Schema; const DataCodeSchema = new Schema({ ...

Issue: Incomplete data retrieval using JS/React fetchDescription: I am facing

I am currently working on an app centered around the card game Magic. The concept involves pasting a list of cards into a textbox and then clicking a button to display corresponding card images. My approach entails using fetch requests to interact with an ...

Is it possible to utilize global variables within CSS properties?

I have a scenario where I need to dynamically change values in an animation. The line of code that needs modification is: clip-path: polygon(var(clip1) 0, 100% 1%, 100% 100%, 50% 100%); let root = document.documentElement; root.style.setProperty('c ...

Adding hue to the portion of text following a JavaScript split() operation

I need assistance in printing the text entered in a textarea with different colors. I am separating the string using the split() method, which works fine. However, I now want to print the substrings in the textarea with colors. How can this be achieved? & ...

Painting Magic: Exploring the World of Canvas Zoom and Moves

I'm having trouble implementing zoom and pan functionality for this particular canvas drawing. While there are examples available for images, my case is different since I am not working with images. Any tips or suggestions on which libraries to use wo ...

Is there a way to assign a dynamic value to an input just once, and then retain the updated value without it changing again

During a for loop, I have an input element (type number) that needs its value modified by decrease and increase buttons: <div class="s-featured-list__item s-featured-list__item--expandable" v-for="(item, itemIndex) in category.items" ...

A guide on displaying a string returned from JavascriptExecutor in Java

Currently, I am attempting to retrieve the string output from JavascriptExecutor called within Java for the first time. While I have looked at various posts on SO, none seem to detail how to successfully extract the string into Java. After scouring the in ...

node.js issue with chalk package

**When I want to use the chalk package in node.js, I encounter the following issue:** index.js const chalk = require('chalk'); console.log(chalk.bgRed.inverse("hello world")); console.log(chalk.blue.inverse('Hello') + &ap ...

The best way to avoid routing before certain async data in the Vuex store has finished loading

I am facing a challenge in my application where I require certain data to be loaded into the VueX store before routing can commence, such as user sessions. An example scenario that showcases a race condition is as follows: // Defined routes { name: &ap ...

Adjustable Bootstrap Progress Bar - Modify element width on the fly

I have encountered an issue with my progress bars on the webpage. The static HTML version works perfectly fine, but the dynamically created one using jQuery seems to be instantly at 100% without any delay in progression. To illustrate the problem better, ...

Error encountered during automatic form submission

My current project involves creating a web notepad that automatically saves changes every minute. The notes are stored in a field called "notas" for each user in the database. Here is some of the code I am using: <html> <head> < ...