如何将JS代码片段存入字符串变量且不修改原代码中的引号?
解决代码片段无修改存入数组的问题
因为你的代码片段同时包含单引号、双引号和反引号,直接用引号包裹会触发语法冲突,以下是几种无需修改原代码的解决方案:
前端浏览器环境:用文本标签存储
将代码片段放在type="text/plain"的script标签中,通过DOM读取内容,完全保留原代码格式:
<script type="text/plain" id="code-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); })(); </script>
在JavaScript中读取并存入数组:
const codeSnippet = document.getElementById('code-snippet').textContent.trim(); const data = [ { id: 1, code: codeSnippet, }, ];
通用方案:用JSON自动转义
无需手动修改代码,借助JSON.stringify自动处理引号转义:
- 打开浏览器控制台,将原代码作为字符串传入
JSON.stringify,复制控制台输出的转义后字符串; - 将转义后的字符串直接赋值给
code字段:
const data = [ { id: 1, 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})();", }, ];
Node.js环境:读取本地文件
将代码片段保存为单独的文本文件(如snippet.txt),通过文件系统模块读取内容:
const fs = require('fs').promises; async function initData() { const codeSnippet = await fs.readFile('./snippet.txt', 'utf8'); const data = [ { id: 1, code: codeSnippet.trim(), }, ]; // 后续业务逻辑处理 } initData();
内容的提问来源于stack exchange,提问作者Ankit Sharma
相关产品推荐
相关产品推荐

