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.
CodePudding user response:
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
where you have to escape backticks (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); })();`;
`
) and dollar signs (${
) - string literal syntax with double quotes
where you have to escape the double quote delimiters (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})();";
"
) and use escape sequences for newline characters (\n
) - multiline string literal syntax with double quotes
where you have to escape the double quote delimiters (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\ })();";
"
) 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