简体   繁体   中英

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 ".

So if the title contains a " like This is a "book" , then obj would be invalid since it would look like:

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?

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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