Reputation: 207
I have a string looks like:
var myString= '{"key1":"value1", "key2":"value2", "key3":"value3"}';
What I want is to remove double qoutes and other special chars only from value3 ... for example some times we have string looks like:
var myString= '{"key1":"value1", "key2":"value2", "key3":"This is "value" with some special chars etc"}';
Please note I do not want to remove double quotes after colon and before This and similarly I do not want to remove last double quotes. I just want to modify string so it will become:
var myString = '{"key1":"value1", "key2":"value2", "key3":"This is value with some special chars etc"}';
Upvotes: 2
Views: 1057
Reputation: 5408
First thing that comes to my mind is to isolate the Value you want.
You can .Split()
for the value you want
var myString = '{"key1":"value1", "key2":"value2", "key3":"value3"}';var n=str.split(" ");
var key3Value = str.split(//Based on your value);//Run .replace() on your key3Value to replace your doublequotes, etc.
//Re-declare myString to include the updated key3Value
Sorry, no time at the moment to finish the code, and I am sure their are better/shorter answers than mine. Just wanted to include this as an option.
Upvotes: 0
Reputation: 32390
You will probably want to use the Array map
function in conjunction with the string replace
function.
To use the replace
function, you'll probably want to use regular expressions. For example, the following regular expression will remove double quotes not immediately after a colon: [^:]"
.
To replace every quote not immediately followed by a colon in an array of strings, you could write this:
var myString= '{"key1":"value1", "key2":"value2", "key3":"value3"}';
var modified = myString.map(function(s) { return s.replace(/[^:]"/g, ''); });
Make your own modifications to the regular expression to match the characters you want to remove.
Refer to http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/.
Upvotes: 0
Reputation: 7100
Simple...
var myNewString = eval( '('+ myString +')');
var toBeEscaped = myNewString.key3;
var escapedString = doYourCleanUpStuff(toBeEscaped);
myNewString.key3 = escapedString;
myNewString = JSON.stringify(myNewString);
===============
What did I do?
1) Your string looks like valid JSON.
2) Cast it into JSON object. (using eval()
)
3) Retrieve value of key3
and catch it in some temp variable.
4) Do cleanup things with this temporary variable.
5) assign cleaned up temporary variable back to key3.
6) Stringify the JSON.
Don't go around beating bush with array manipulation and split functions, especially when there are simpler ways :)
Upvotes: 2