0

I'm trying to make an app that displays code snippets, for that, I'm creating a data array (so that I can use a map function on that data to display a list of code)

it should contain the following contents -

const data = [
  {
    id: 1,
    code: "The code goes here.",
  },
];

However, whenever I try to enclose this snippet -

javascript: (() => {
  var word = prompt(`Please enter the word here. `);

  const call = async (word) => {
    const request = await fetch(
      `https://www.dictionaryapi.com/api/v3/references/thesaurus/json/${word}?key=`
    )
      .then((response) => response.json())
      .then((data) => {
        const synArray = data[0].meta.syns[0];
        window.alert(synArray);
      });
  };

  call(word);
})();

In double quotes or single quotes. It does not work. I want exactly this snippet to be stored in a variable. I don't want to change the single quotes or any other thing in the code itself.

Ankit Sharma
  • 164
  • 8
  • i don't think you can do that – OldProgrammer Jul 31 '22 at 15:16
  • When the javascript compiler is reading the file all it sees is a stream of characters. It has no idea that a valid block of JS is not supposed to be something it should run. Thus, you're going to need to change the contents of the code to escape it such that the js compiler sees it as what you intend it to be, a string. – Luke Briggs Jul 31 '22 at 15:18
  • 1
    _"I don't want to change the single quotes or any other thing in the code itself."_ - There are rules a string has to fulfill. – Andreas Jul 31 '22 at 15:21
  • 1
    Use `JSON.stringify` to properly escape a long string value (such as the text you have) as a string. – Bergi Jul 31 '22 at 15:22
  • @LukeBriggs can you possibly explain how I can use escape my code snippet to let the compiler know that it is a string? – Ankit Sharma Jul 31 '22 at 15:27
  • 1
    "*I'm trying to make an app that displays code snippets*" - where do you want to store them, and how do you want to author them? In a normal app, you'd put them in a database, not hardcode them in some javascript code. – Bergi Jul 31 '22 at 16:02
  • @Bergi It's going to be a small application so I don't see a point in setting up a database for it, I'm just storing this data in a data.js file in an array because there will be 10-15 items. – Ankit Sharma Jul 31 '22 at 19:02
  • 1
    @AnkitSharma Then you have to live with doing the escaping yourself. You really should consider storing each snippet in a separate file, and reading these files. – Bergi Jul 31 '22 at 19:56

1 Answers1

1

I don't want to change the single quotes or any other thing in the code itself.

There's no way around that if you want to write a string literal containing quotes or the respective delimiters in a javascript file.

You can use either:

  • template literal syntax
    const code = `javascript: (() => {
      var word = prompt("Please enter the word here. ");
    
      const call = async (word) => {
        const request = await fetch(
          \`https://www.dictionaryapi.com/api/v3/references/thesaurus/json/\${word}?key=\`
        )
          .then((response) => response.json())
          .then((data) => {
            const synArray = data[0].meta.syns[0];
            window.alert(synArray);
          });
      };
    
      call(word);
    })();`;
    
    where you have to escape backticks (`) and dollar signs (${)
  • string literal syntax with double quotes
    const code = "javascript: (() => {\n  var word = prompt(\"Please enter the word here. \");\n\n  const call = async (word) => {\n    const request = await fetch(\n      `https://www.dictionaryapi.com/api/v3/references/thesaurus/json/${word}?key=`\n    )\n      .then((response) => response.json())\n      .then((data) => {\n        const synArray = data[0].meta.syns[0];\n        window.alert(synArray);\n      });\n  };\n\n  call(word);\n})();";
    
    where you have to escape the double quote delimiters (") and use escape sequences for newline characters (\n)
  • multiline string literal syntax with double quotes
    const code = "javascript: (() => {\n\
      var word = prompt(\"Please enter the word here. \");\n\
    \n\
      const call = async (word) => {\n\
        const request = await fetch(\n\
          `https://www.dictionaryapi.com/api/v3/references/thesaurus/json/${word}?key=`\n\
        )\n\
          .then((response) => response.json())\n\
          .then((data) => {\n\
            const synArray = data[0].meta.syns[0];\n\
            window.alert(synArray);\n\
          });\n\
      };\n\
    \n\
      call(word);\n\
    })();";
    
    where you have to escape the double quote delimiters (") and linebreaks and use escape sequences for newline characters (\n)
  • string literals syntax with apostrophes, which work just like those with double quotes, except you have to escape apostrophes (') instead.
  • see also Creating multiline strings in JavaScript
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thank you so much for your answer, It is super useful. I figured that I can change a few things in the code snippet and it will still work the same way. So I'm going with the template literal syntax however I just used a + operator to join different parts of the URL to make it into a single URL. These snippets are supposed to be used as Bookmarklets, and google doesn't accept double quotes in bookmarklets and a few more rules which were the main reason I didn't wanted to change the code. Thanks. – Ankit Sharma Jul 31 '22 at 21:00