skip to Main Content

When passing the text in SQL query that has qoutes (for example: I’m –text—) that ‘ in I’m needs to be doubled up so that server won’t crash.

How to do that in javascript? Is there some NPM package or a way to loop through the text and double up the qoutes?

Here is my SQL text:

queryText = `INSERT INTO posts (id, user_id, title, content, image_urls) VALUES(uuid_generate_v4(), '${req.user.id}', '${title}', '${content}', ARRAY [${realImages}] ) RETURNING *`;

2

Answers


  1. Try this, I tested this and it worked for me:
    ( Just double quote beside the single ones )

    queryText = INSERT INTO posts (id, user_id, title, content, image_urls) VALUES(uuid_generate_v4(), '"${req.user.id}"', '"${title}"', '${content}', ARRAY [${realImages}] ) RETURNING *;
    

    P.S. Also one tip that I encounter, I think uuid_generate_v4() in your code should be ${uuid_generate_v4()}, right?

    Login or Signup to reply.
  2. From what I understood, you want to double the quotes in a string.

    The question now is: Do you want to transform simple quotes to double quotes, or do you want to double the amount of quotes?

    The both cases will look like:

    ' -> ''

    ' -> "

    And for the worth cases you will need the function replace.

    You can use it this way :

    let queryText = `INSERT INTO posts (id, user_id, title, content, image_urls) VALUES(uuid_generate_v4(), '${req.user.id}', '${title}', '${content}', ARRAY [${realImages}] ) RETURNING *`;
    
    // First case
    queryText  = queryText.replace(`'`, `''`);
    
    // Second case
    queryText  = queryText.replace(`'`, `"`);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search