简体   繁体   English

Javascript生成的字符串问题中的双引号

[英]Double-quotes in a Javascript generated string issue

I am loading some text from a file in a node js application using something similar to the following: 我正在使用类似于以下内容的方法从节点js应用程序中的文件加载一些文本:

var retr = fs.readFileSync( __dirname + tmp).toString();

The files contains a string similar to: a"a 该文件包含类似的字符串: a"a

I am using that string to generate a constant value using double quotes: 我正在使用该字符串使用双引号生成一个常量值:

var MY_CT ="a"a";

Of course, node complains this code is not valid. 当然,节点抱怨此代码无效。

How can I transform the double-quotes to init MY_CT properly? 如何将双引号正确转换为初始化MY_CT I can't modify the source file itself. 我无法修改源文件本身。 The source file is not HTML, it is plain text. 源文件不是HTML,而是纯文本。

What I understood is that you have a variable (let's call it x ) which contains a random string, read from a file, which can contain single quotes or double quotes and you want to generate a file containing that string between quotes so it can be interpreted in JavaScript. 我了解的是,您有一个变量(将其称为x ),该变量包含一个随机字符串,可从文件中读取,该文件可以包含单引号或双引号,并且您想生成一个文件,在引号之间包含该字符串,因此可以用JavaScript解释。

The solution would be: 解决方案是:

JSON.stringify(x)

This will return in your case: "a\\"a" which is valid. This will also work when your file contains single quotes. 这将在您的情况下返回: "a\\"a"有效。当您的文件包含单引号时,它也将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM