7

I did a search through the site, but it's still not working.

var blah2 = JSON.stringify({foo: 123, bar: <x><y></y></x>, baz: 123});

this is what I tried:

blah2.replace(/[{}]/g, "");

this is what it the string comes out to:

got "{\"baz\":123,\"foo\":123}"

(i know this is probably a newb question, but this is my first time working with javascript and i just don't know what i'm missing)

nocturn4l toyou
  • 403
  • 2
  • 5
  • 5

2 Answers2

21

Javascript strings are immutable. When you call blah2.replace, you are not replacing something inside blah2, you are creating a new string. What you probably want is:

blah2 = blah2.replace(/[{}]/g, '');
ziad-saab
  • 19,139
  • 3
  • 36
  • 31
  • i would up vote you but it wont' let me. TYVM!!! trying to fix a bug in Firefox, was driving me nuts. ty. will accept answer in 10 min when it lets me – nocturn4l toyou May 29 '12 at 03:03
0

because i'm going to split it with the comma so it turns into an array, and so when I sort it, I dont want to sort it according to the { and }

zi42 has already given you the correct answer.

But Since you have written as quoted above, looks like what you want is really to sort data and split it in an array; in this case, parsing/splitting it at the comma, etc, is a long way to go about it. Here's another way to think about it:

var data = {foo: 123, bar: <x><y></y></x>, baz: 123};
var key;
var dataSorted = []; // Create an empty array

for (key in data) {  // Iterate through each key of the JSON data
  dataSorted.push(key);
}

dataSorted.sort();

Now you have the data sorted. When you want to use it, you can use it like this:

for (var i = 0; i < dataSorted.length; i++) {
  var key = dataSorted[i];
  // Now you do whatever you need with sorted data. eg:
  console.log("Key is: " + key + ", value is: " + data[key]);
}
Kayo
  • 966
  • 1
  • 7
  • 16