簡體   English   中英

保存包含單引號和雙引號的字符串?

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

我有一個看起來像下面的對象:

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

this.book.title是一個字符串,可以包含未轉義的單引號'或雙引號'。

因此,如果標題包含“ like This is a "book" ,則obj無效,因為它看起來像:

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

有沒有比this.book.title = this.book.title.replace(/(['"])/g, "\\\\$1");更好的方法來轉義引號?

您的問題不是很清楚,但似乎您想要的是:

 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