Ujjwal Kumar Gupta
Ujjwal Kumar Gupta

Reputation: 2376

regex replace certain character but not for particular set in javascript

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

Answers (4)

Kobi
Kobi

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

  • 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

Upvotes: 0

Dinesh undefined
Dinesh undefined

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

Tushar
Tushar

Reputation: 87203

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'));

Upvotes: 2

sorak
sorak

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

Related Questions