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.

2
  • 2
    .replace(/(\w+)\s*=\s*(\w+)/g, '$1 $2') Commented Dec 19, 2017 at 4: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. Commented Dec 19, 2017 at 5:04

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

Simple and dirty trick. Remove g from regx

var str='select * from where item1=abcd and price>=20';
console.log(str.replace(/[=]/, " "))

1 Comment

Won't work if there are multiple conditions or the <=, >= or == condition appears before =.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.