qimisle
qimisle

Reputation: 75

Javascript: cannot replace two double quotes with a single doublequote

value is "//a[@class="post-tag"]" and I am trying to remove the two double quotes from the jsonString which returns ""//a[@class=\"post-tag\"]""

                            var jsonString = JSON.stringify(value);
                            var cleanjson = jsonString.replace(/""/g, '"');

I don't understand why this simple example is not working. jsonString returns ""//a[@class=\"post-tag\"]"" and I am trying to replace the two doublequotes with a single one. However, cleanjson will still have the two double quotes.

Upvotes: 0

Views: 157

Answers (2)

blex
blex

Reputation: 25634

It might be simpler to trim the outer quotes before stringifying it:

var value = '"//a[@class="post-tag"]"';

// Remove quotes at the beginning and end
var trimmed = value.replace(/(^"|"$)/g, '');
console.log(trimmed);    // -> //a[@class="post-tag"]

// Escape remaining quotes and add outer quotes back
var escaped = JSON.stringify(trimmed);
console.log(escaped);    // -> "//a[@class=\"post-tag\"]"

Upvotes: 0

Benoit Esnard
Benoit Esnard

Reputation: 2075

You can't remove the two double quotes because they aren't present in your variable

The value of the jsonString variable is "//a[@class="post-tag"]", but because it is a string, it will be displayed encapsulated in double quotes: ""//a[@class="post-tag"]""

Upvotes: 2

Related Questions