简体   繁体   English

保存包含单引号和双引号的字符串?

[英]Saving a string that contains both single and double quotes?

I have an object that looks like the following: 我有一个看起来像下面的对象:

obj = {book: `{title: "${this.book.title}"}`}

this.book.title is a string that could contain unescaped single quote ' or double quote ". this.book.title是一个字符串,可以包含未转义的单引号'或双引号'。

So if the title contains a " like This is a "book" , then obj would be invalid since it would look like: 因此,如果标题包含“ like This is a "book" ,则obj无效,因为它看起来像:

obj = {book: `{title: "This is a "book""}`}

Is there a better way than doing this.book.title = this.book.title.replace(/(['"])/g, "\\\\$1"); to escape the quotes? 有没有比this.book.title = this.book.title.replace(/(['"])/g, "\\\\$1");更好的方法来转义引号?

Your question isn't super clear, but it seems like what you want is this: 您的问题不是很清楚,但似乎您想要的是:

 this.book = { title: 'This is a "book"' }; const obj = { book: JSON.stringify({ title: this.book.title }) }; console.log(obj); // <- this is an object console.log(obj.book); // <- this is a string 

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

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