Converting String to Array and back in Javascript - javascript

I simply have a huge array in a string like this:
"test", "blabla", "anothertest", "et", "cetera"
I need to be able to convert it to an array, preferable without the " "'s still left over.
I have no idea how javascript would be able to do this, but I heard JSON was able to do something like this.

JSON is fine indeed:
var string = '"test", "blabla", "anothertest", "et", "cetera"';
JSON.parse('[' + string + ']');
Keep in mind that string must respect the JSON syntax. More precisely, you have to check that double quotes are used, the separator is a comma and so on.

If your string contains data in quotes, and separated with comma, it almost valid json. Just do this
var myparsedarray = JSON.parse("[" + yourstring + "]");

Related

JS Change string format

I have a string in the following format :
One,Two,Three,Four
and I want to change its format to "One","Two","Three","Four"
I tried the following :
var items = ['One,Two,Three,Four'];
var quotedAndCommaSeparated = '"' + items + '"';
document.write(quotedAndCommaSeparated);
which adds the double quotes at the beginning and at the end of the string. I don't want to use replace because there might be values that have a comma.
Is there a way to split the initial string and return the wanted one?
Try this
items[0].replace(/^|$/g, '"').replace(/,/g,'","')
This should give you what you want. Split on the commas and then rejoin using the delimiter you are looking for.
var quotedAndCommaSeparated = '"'+items[0].split(',').join('","')+'"'

Convert string to Json in Javascript

My string is like this :
"['01',746],['02',0],['03',9994],['04',0],['05',0],['06',0],['07',0],['08',0],['09',0],['10',0],['11',0],['12',0],['13',0],['14',0],['15',0],['16',0],['17',0],['18',0],['19',0],['20',0],['21',0],['22',0],['23',0],['24',0],['25',0],['26',0],['27',0],['28',0],['29',0],['30',0],['31',0]"
I have tried $.parseJSON() or JSON.Parse() but does not work . I am gonna use this data for google chart . so i need it in the json format .
how can i do that ?
You need to convert the single quotes to double to be valid and you would need to wrap it in [] so it is a valid array format.
var str = "['01',746],['02',0],['03',9994],['04',0],['05',0],['06',0],['07',0],['08',0],['09',0],['10',0],['11',0],['12',0],['13',0],['14',0],['15',0],['16',0],['17',0],['18',0],['19',0],['20',0],['21',0],['22',0],['23',0],['24',0],['25',0],['26',0],['27',0],['28',0],['29',0],['30',0],['31',0]";
var myArray = JSON.parse("[" + str.replace(/'/g,'"') + "]");
console.log(myArray[0][0], myArray[0][1]); // "01" 746
But a better solution is to fix what is producing that string so it is a valid JSON object to start.

JSON Parsing using regex

I'd like to know if I can parse & filter JSON text data based on a regular expression; say for example I have the following
{"key":"some:xx:yy", "value": 72311}
{"key":"some:xx:zz", "value": 72311}
{"key":"some:xx:qq", "value": 72311}
I want to select all tuples that have for the key field the same "some:xx:" part, how can I archive this using JSON in an 'elegant' way?
The example you gave contains three different objects. So you can use javascript to look for text in a property.
obj1 = {"key":"some:xx:yy", "value": 72311};
if (obj1.key.indexOf("xx") !== -1) { // obj1.key contains "xx"
//do something
}
If you have an array with those values, then you can simply loop through the array and look for "xx" just like above for each element of array. And when found, you can assign that element to another array. So at the end of the loop, "another array" will contain all elements that contain "xx".
If you don't insist on using RegEx, i can show you an example code for the loop. If you insist on RegEx, let me know and i will help you.. just kidding, let me know and i will delete my answer and silently leave this question :)
I'm going to give you a straight answer to the question you asked, but hopefully the complexity and the raft of caveats will convince you that JSON.parse is a better alternative.
You can write a regular expression to match a single such tuple, but you can't write a regular expression to match all such tuples.
To explain why, consider the regular expression that matches one:
var stringBody = '(?:[^"\\\\]|\\\\.)*';
var string = '"' + stringBody + '"';
var space = '[ \t\r\n\f]*';
var colon = space + ':' + space;
var comma = space + ',' + space;
var uglyRegex = '^(?:[^"]|' + string + ')*?'
+ '"key"' + colon + '"(some:xx:' + stringBody + ')"' + comma
+ '"value"' + colon + '((?:[^\},"]|' + string + ')*)';
This works by finding the minimal number of non-string or full-string tokens that precede a key whose value starts with some:xx: and then looks for a value.
It leaves the key in matching group 1 and the value in matching group 2.
Since it has to match starting at the beginning to correctly identify string token boundaries, it cannot be used in a 'g' flag match.
Caveats
It assumes certain characters in "key"'s property value are not \uABCD escaped.
It assumes characters in the property names "key" and "value" are not \uABCD escaped.
It requires the key and value to occur in that order.
It cannot tell what other properties occur in the same object.
Each of these problems could be worked around by making the regex much more complex, but with regular expressions, often, the only way to handle a corner case is to make the regex much bigger.
When incremental improvements to code explode the size, the code is unmaintainable.

How to achieve following result in Javascript?

I have a code like this:
var exist_file = document.getElementById('exist_file').value;
document.getElementById('dialog-confirm-upload').innerHTML=
"The file" +
for (var i=0;i<exist_file.length;i++){
exist_file + ","
}
+
"has been already transferred? Do you want to overwrite?"
exist_file is an array which contains one or more than one element: ['hello', 'ok']. I want to pass the value to innerHTML like this.
"The file hello, ok has been already transferred? Do you want to overwrite?" I tried the following above code but it turns out that's not a valid syntax. How can I achieve this?
First you have to parse the string into an array, then you can format it with commas:
var exist_file = document.getElementById('exist_file').value;
document.getElementById('dialog-confirm-upload').innerHTML=
"The file " +
exist_file.substr(3, exist_file.length - 5).split("', u'").join(", ") +
" has already been transferred. Do you want to overwrite?"
Note: This is the most basic form of parsing. It works with strings containing regular characters, but escaped characters are not unescaped.
var exist_file = document.getElementById('exist_file').value,
msg = "The file" + exist_file.toString() + "has been already transferred? Do you want to overwrite?";
document.getElementById('dialog-confirm-upload').innerHTML= msg;
This snippet works for both cases where exist_file is an array or a string.

Why do you need the + between variables in javascript?

Why does this line work
$('#body-image').css("background-image", 'url('+ backgroundimage +')');
but not this one
$('#body-image').css("background-image", 'url('backgroundimage')');
or this one
$('#body-image').css("background-image", 'url(backgroundimage)');
backgroundimage is a JavaScript variable. The concatenation operator in JavaScript is +, so to put a string together with a variable, you do 'some string ' + someVariable. Without the +'s, JavaScript wouldn't know what to do with your variable (and in your third example, wouldn't even know that it was a variable).
You need to concat the string with the variable backgroundimage. So you use "+" for this.
That's why this doesn't work.
$('#body-image').css("background-image", 'url('backgroundimage')');
And the secont doesn't work because there is no image called 'backgroundimage'.
$('#body-image').css("background-image", 'url(backgroundimage)');
Because you are building a string. You are missing the line where backgroundimage gets a value:
var backgroundimage = "someimage.gif";
$('#body-image').css("background-image", 'url('+ backgroundimage +')');
becomes:
$('#body-image').css("background-image", 'url(someimage.gif)');
it's concatenating the string.
let's say backgroundimage is 'foo.jpg, then
'url('+backgroundimage+')' = 'url(foo.jpg)'
In JavaScript, a string literal (i.e., "I am a string") is actually treated like a String object (though, strictly speaking, it isn't - see the MDC documentation - but we can ignore the difference at this level). The following two lines are equivalent:
var letters = "ABC", numbers = "123";
var letters = new String("ABC"), numbers = new String("123");
Strings are concatenated using either the + operator or the String.concat method, either of which join 2 or more strings in a left-to-right order and return the result. So in order to get "ABC123", we can do any of the following:
"ABC" + "123"
"ABC" + numbers
letters + "123"
letters + numbers
"ABC".concat("123")
"ABC".concat(numbers)
letters.concat("123")
letters.concat(numbers)
but not:
letters"123"
"ABC"numbers
lettersnumbers
"lettersnumbers"
which are all, effectively, the same thing that you were trying to do in your examples.

Categories

Resources