How to Convert Array-like String to Array - javascript

I have a string that looks like an array: "[918,919]". I would like to convert it to an array, is there an easier way to do this than to split and check if it is a number? Thanks

Use JSON.parse.
var myArray = JSON.parse("[918,919]");

You can get rid of the brackets at the beginning and the end, then use:
str.split(",")
which will return an array split by the comma character.
EDIT
var temp = new Array();
temp = "[918,919]".slice( 1, -1).split(",");
for (a in temp ) {
temp[a] = parseInt(temp[a]);
}

If you use JSON.parse the string must have " and not ' otherwise the code will fail.
for example:
let my_safe_string = "['foo','bar',123]";
let myArray = JSON.parse(my_safe_string)
the code will fail with
Uncaught SyntaxError: Unexpected token ' in JSON at position 1
instead if you use " all will work
let my_safe_string = "["foo","bar",123]";
let myArray = JSON.parse(my_safe_string);
so you have two possibility to cast string array like to array:
Replace ' with " my_safe_string.replace("'",'"'); and after do JSON.parse
If you are extremely sure that your string contain only string array you can use eval:
example:
let myArray = eval(my_safe_string );

Related

How change a string looks like array to a real aray

I have a string, it looks like a array but not a real array. So my question is how to make it to a real array.
let string = "["abc", "cde"]";
// how to make string become an array
change string to an array
First you need to make sure your string is invalid format
"["abc", "cde"]" // invalid
"[abc, cde]" // invalid
"[11, 22]" // valid,if you do not want to use quote to wrap it,then the elements need to be number
"['abc', 'cde']" // valid
let string = `["abc", "cde"]`
const array = JSON.parse(string)
console.log(array)
You can do something like this
let data = "['abc', 'pqr', 'xxx']";
data = data.replace(/'/g, '"');
console.log(data)
const convertedArray = JSON.parse(data);
console.log(convertedArray)
Observation : Your input string is not a valid JSON string.
Solution : Double quotes besides the array items should be escaped to parse it properly. Your final string should be.
let string = "[\"abc\", \"cde\"]";
Now you can parse it using JSON.parse() method.
Live Demo :
let string = "['abc', 'cde']";
string = string.replace(/'/g, '"');
console.log(string); // "[\"abc\", \"cde\"]"
console.log(JSON.parse(string)); // ["abc", "cde"]

Alternative eval() to execute the string

My array is A=['Apple','Peach','Orange']in Javascript, someone pass me the string like "A[1]" , how to convert the string "A[1]" to an executable item, so I can get 'Peach' as the result.
eval(A[1]) used to work but is not allowed here.
Using regex you can parse out the variable and the index, then grab them off the window object.
A=['Apple','Peach','Orange'];
let string = "A[1]";
let variable = string.match(/[^[]*/)[0];
let index = string.match(/\[(.*)\]/)[1];
console.log(window[variable][index]);
You could split by apostrophe and then filter out the odd array members:
var arrayString = "A=['Apple','Peach','Orange']"
var parsed = arrayString.split("'").filter(function(a, b){return b % 2});
console.log(parsed)

How to convert array defined in string variable with \r\n using Javascript?

I have a string variable with array data .
var str = "[\r\n  10,\r\n  20\r\n]" ;
I want to convert above string to array like using javascript .
Output :-
var arr = [10,20];
You can simply use JSON.parse - it will ignore the newlines and convert the string representation of an array to a JavaScript array:
var str = "[\r\n 10,\r\n 20\r\n]" ;
var arr = JSON.parse(str);
console.log(Array.isArray(arr))
console.log(arr)
You need only to parse that string as a JSON, because it is clearly an array.
So this is the procedure:
var str = "[\r\n 10,\r\n 20\r\n]";
const myArray = JSON.parse(str);
console.log(myArray);
UPDATE:
If you are wondering why those special chars (\r\n) are going away:
// a string
const str = "[\r\n 10,\r\n 20\r\n]";
// if I print out this, Javascript, will automatically replace those special
// chars with what they means (new line)
console.log(str);
console.log(typeof(str));
// so if we are going to parse our string to the JSON parser
// it will automatically transform the special chars to new lines
// and then convert the result string "[10,20]" to an array.
const myArray = JSON.parse(str);
console.log(myArray);
console.log(typeof(myArray));

Converting int array in string format to array

I have an array of integers stored in string format.
eg:
"[3,2,1]"
How can I convert this to an actual array?
I've searched high and low for a simple solution but I can't seem to find it.
Passing the string into JSON.parse and $.parseJSON results in "[" being shown for the 0 index. So I'm assuming it's not doing anything.
var arr = JSON.parse("[3,2,1]")
var text = "[3,2,1]";
var obj = JSON.parse(text);
console.log(obj);
You could use jQuery $.parseJSON() method :
var arr = $.parseJSON("[3,2,1]");
var str = "[3,2,1]";
console.log( $.parseJSON(str) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or pure javascript method JSON.parse() :
var arr = JSON.parse("[3,2,1]");
Hope this helps.
var str = "[3,2,1]";
console.log( JSON.parse("[3,2,1]") );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So I've figured out I needed to slice the first and last characters off as for some reason the string was being returned as ""[3,2,1]"" rather than "[3,2,1]" even though it's stored without quotes.
From your updated description it appears you have a string that starts and ends with ", so a simple JSON.parse will not work, since that will just convert what's between the "'s to a string. You need to either JSON.parse twice, since you have an array of integers embedded in a string, or manually parse.
JSON.parse twice way:
var str = '"[3,2,1]"';
var parsedStr = JSON.parse(str); // results in a string with contents [3,2,1]
var intArray = JSON.parse(parsedStr); // results in an int array with contents [3,2,1]
Or, if format could change to be non-JSON at some point, manual way:
var str = '"[3,2,1]"';
var intArray = [];
str.substr(2,str.length-3).split(/,/g).forEach(function(numStr) {
intArray.push(parseInt(numStr));
});

Convert string with commas to array

How can I convert a string to a JavaScript array?
Look at the code:
var string = "0,1";
var array = [string];
alert(array[0]);
In this case alert shows 0,1. If it where an array, it would show 0. And if alert(array[1]) is called, it should pop-up 1
Is there any chance to convert such string into a JavaScript array?
For simple array members like that, you can use JSON.parse.
var array = JSON.parse("[" + string + "]");
This gives you an Array of numbers.
[0, 1]
If you use .split(), you'll end up with an Array of strings.
["0", "1"]
Just be aware that JSON.parse will limit you to the supported data types. If you need values like undefined or functions, you'd need to use eval(), or a JavaScript parser.
If you want to use .split(), but you also want an Array of Numbers, you could use Array.prototype.map, though you'd need to shim it for IE8 and lower or just write a traditional loop.
var array = string.split(",").map(Number);
Split it on the , character;
var string = "0,1";
var array = string.split(",");
alert(array[0]);
This is easily achieved in ES6;
You can convert strings to Arrays with Array.from('string');
Array.from("01")
will console.log
['0', '1']
Which is exactly what you're looking for.
If the string is already in list format, you can use the JSON.parse:
var a = "['a', 'b', 'c']";
a = a.replace(/'/g, '"');
a = JSON.parse(a);
Convert all type of strings
var array = (new Function("return [" + str+ "];")());
var string = "0,1";
var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';
var stringArray = (new Function("return [" + string+ "];")());
var objectStringArray = (new Function("return [" + objectstring+ "];")());
JSFiddle https://jsfiddle.net/7ne9L4Lj/1/
Result in console
Some practice doesnt support object strings
- JSON.parse("[" + string + "]"); // throw error
- string.split(",")
// unexpected result
["{Name:"Tshirt"", " CatGroupName:"Clothes"", " Gender:"male-female"}", " {Name:"Dress"", " CatGroupName:"Clothes"", " Gender:"female"}", " {Name:"Belt"", " CatGroupName:"Leather"", " Gender:"child"}"]
For simple array members like that, you can use JSON.parse.
var listValues = "[{\"ComplianceTaskID\":75305,\"RequirementTypeID\":4,\"MissedRequirement\":\"Initial Photo Upload NRP\",\"TimeOverdueInMinutes\":null}]";
var array = JSON.parse("[" + listValues + "]");
This gives you an Array of numbers.
now you variable value is like array.length=1
Value output
array[0].ComplianceTaskID
array[0].RequirementTypeID
array[0].MissedRequirement
array[0].TimeOverdueInMinutes
You can use split
Reference:
http://www.w3schools.com/jsref/jsref_split.asp
"0,1".split(',')
Another option using the ES6 is using Spread syntax.
var convertedArray = [..."01234"];
var stringToConvert = "012";
var convertedArray = [...stringToConvert];
console.log(convertedArray);
use the built-in map function with an anonymous function, like so:
string.split(',').map(function(n) {return Number(n);});
[edit] here's how you would use it
var string = "0,1";
var array = string.split(',').map(function(n) {
return Number(n);
});
alert( array[0] );
How to Convert Comma Separated String into an Array in JavaScript?
var string = 'hello, world, test, test2, rummy, words';
var arr = string.split(', '); // split string on comma space
console.log( arr );
//Output
["hello", "world", "test", "test2", "rummy", "words"]
For More Examples of convert string to array in javascript using the below ways:
Split() – No Separator:
Split() – Empty String Separator:
Split() – Separator at Beginning/End:
Regular Expression Separator:
Capturing Parentheses:
Split() with Limit Argument
check out this link
==> https://www.tutsmake.com/javascript-convert-string-to-array-javascript/
You can use javascript Spread Syntax to convert string to an array. In the solution below, I remove the comma then convert the string to an array.
var string = "0,1"
var array = [...string.replace(',', '')]
console.log(array[0])
I remove the characters '[',']' and do an split with ','
let array = stringObject.replace('[','').replace(']','').split(",").map(String);
More "Try it Yourself" examples below.
Definition and Usage
The split() method is used to split a string into an array of substrings, and returns the new array.
Tip: If an empty string ("") is used as the separator, the string is split between each character.
Note: The split() method does not change the original string.
var res = str.split(",");
Regexp
As more powerful alternative to split, you can use match
"0,1".match(/\d+/g)
let a = "0,1".match(/\d+/g)
console.log(a);
Split (",") can convert Strings with commas into a String array, here is my code snippet.
var input ='Hybrid App, Phone-Gap, Apache Cordova, HTML5, JavaScript, BootStrap, JQuery, CSS3, Android Wear API'
var output = input.split(",");
console.log(output);
["Hybrid App", " Phone-Gap", " Apache Cordova", " HTML5", "
JavaScript", " BootStrap", " JQuery", " CSS3", " Android Wear API"]
var i = "[{a:1,b:2}]",
j = i.replace(/([a-zA-Z0-9]+?):/g, '"$1":').replace(/'/g,'"'),
k = JSON.parse(j);
console.log(k)
// => declaring regular expression
[a-zA-Z0-9] => match all a-z, A-Z, 0-9
(): => group all matched elements
$1 => replacement string refers to the first match group in the regex.
g => global flag
Why don't you do replace , comma and split('') the string like this which will result into ['0', '1'], furthermore, you could wrap the result into parseInt() to transform element into integer type.
it('convert string to array', function () {
expect('0,1'.replace(',', '').split('')).toEqual(['0','1'])
});
Example using Array.filter:
var str = 'a,b,hi,ma,n,yu';
var strArr = Array.prototype.filter.call(str, eachChar => eachChar !== ',');

Categories

Resources