Reputation: 2376
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.
Upvotes: 2
Views: 495
Reputation: 138007
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
(
...)
, which is captured into $1
.
>=
and <=
. I also threw in ==
(is this valid in SQL?) and escaped SQL strings, just for the example.=
.This approach is explained nicely here: Regex Pattern to Match, Excluding when... / Except between
Upvotes: 0
Reputation: 5546
Simple and dirty trick. Remove g
from regx
var str='select * from where item1=abcd and price>=20';
console.log(str.replace(/[=]/, " "))
Upvotes: 0
Reputation: 87203
Use below regex for replacement
/([a-z0-9]+)\s*=\s*([a-z0-9]+)/gi
and replace it with $1 $2
.
([a-z0-9]+)
: Match one or more alphanumeric characters and add them to capturing group\s*
: Zero or more space characters=
: Equal signgi
: 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'));
Upvotes: 2
Reputation: 2633
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.
Upvotes: 1