Want to remove bracelets from a thread

I did a search on the site, but it still does not work.

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

here is what i tried:

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

this is what the line outputs:

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

(I know this is probably a newb question, but this is my first experience with javascript, and I just don't know what I am missing)

+4
source share
2 answers

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

 blah2 = blah2.replace(/[{}]/g, ''); 
+10
source

because I’m going to break it with a comma so that it turns into an array, and therefore, when I sort it, I don’t want to sort it according to {and}

zi42 already gave you the correct answer.

But since you wrote above, it looks as if you want to sort the data and break it into an array; in this case, parsing / breaking it into a comma, etc. is a long way to go. Here is 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(); 

You have now sorted the data. When you want to use it, you can use it as follows:

 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]); } 
0
source

Source: https://habr.com/ru/post/1414805/


All Articles