2
var str='select * from where item1=abcd and price>=20';

I am using the below code to replace the '=' to empty space

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

but it is also replacing '>=' . I want >= not to be replaced with any thing and also for some others condition like '==' or '<=' etc.

So my output should be - 'select * from where item abcd and price>=20'

Please help me to achieve this.

Star
  • 3,222
  • 5
  • 32
  • 48
Ujjwal Kumar Gupta
  • 2,308
  • 1
  • 21
  • 32
  • 2
    [`.replace(/(\w+)\s*=\s*(\w+)/g, '$1 $2')`](https://regex101.com/r/gkwEfR/1) – Tushar Dec 19 '17 at 04:59
  • thanks, this is working. but i am not able to understand this. Can you please describe more about this or you can point to some tutorial? I will accept this as answer. – Ujjwal Kumar Gupta Dec 19 '17 at 05:04

4 Answers4

2

Use below regex for replacement

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

and replace it with $1 $2.

  1. ([a-z0-9]+): Match one or more alphanumeric characters and add them to capturing group
  2. \s*: Zero or more space characters
  3. =: Equal sign
  4. gi: g: Global flag to match all possible matches. i: Case-insensitive flag.

$n in the replacement part is the nth captured group value.

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

console.log(str.replace(regex, '$1 $2'));
Tushar
  • 85,780
  • 21
  • 159
  • 179
1

Replace an equal sign with a letter or number on either side with the corresponding characters around a space.

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

In regex [] means "the set of", so [a-zA-Z0-9] is one character from the set of any lowercase, uppercase, or digit.

sorak
  • 2,607
  • 2
  • 16
  • 24
0

Simple and dirty trick. Remove g from regx

var str='select * from where item1=abcd and price>=20';
console.log(str.replace(/[=]/, " "))
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40
  • 2
    Won't work if there are multiple conditions or the `<=`, `>=` or `==` condition appears before `=`. – Tushar Dec 19 '17 at 05:15
0

A good way to approach these problems is to capture everything you wish to skip, and then not capture everything you wish you remove. In your case:

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

and replace with $1.

Working example: https://regex101.com/r/3pT9ib/3

  • First we have a capturing group: (...), which is captured into $1.
    • The group matched >= and <=. I also threw in == (is this valid in SQL?) and escaped SQL strings, just for the example.
  • If we were not able to match the group, we can safely match and remove the leftover =.

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

Kobi
  • 135,331
  • 41
  • 252
  • 292