Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
979 views
in Technique[技术] by (71.8m points)

jquery - JavaScript - Escape double quotes

How do you escape double quotes if the JSON string is the following?

var str = "[{Company: "XYZ",Description: ""TEST""}]"

I want to escape the secondary double quotes in value TEST.

I have tried the following, but it does not work.

var escapeStr = str.replace(/""/g,'"');

What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It should be:

var str='[{"Company": "XYZ","Description": ""TEST""}]';

First, I changed the outer quotes to single quotes, so they won't conflict with the inner quotes. Then I put backslash before the innermost quotes around TEST, to escape them. And I escaped the backslash so that it will be treated literally.

You can get the same result with use of a JSON function:

var str=JSON.stringify({Company: "XYZ", Description: '"TEST"'});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...