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));
Yesterday i solve my problem spliting my string with "\" but today i have the same problem but with a object...
2|wscontro | [2017-05-31 15:57:23.145] - debug: /opt/wscontroller/wscontroller-api/routes/ubus UbusController 63320169-611e-43f5-880e-9b1a13152cfd getDeviceServicesById signature {"config":"wireless","section":"radio0","values":"{\"disabled\":0}"}
2|wscontro | [2017-05-31 15:57:23.145] - debug: /opt/wscontroller/wscontroller-api/routes/ubus UbusController 63320169-611e-43f5-880e-9b1a13152cfd getDeviceServicesById signature "object"
I need to have only signature =>
{"config":"wireless","section":"radio0","values":{"disabled":0"}}
Can anyone help me? I try to convert to String this object and split doing
var aux = signature.split('\\').join('');
var jsonObject = JSON.parse(aux);
But i get the same result {"config":"wireless","section":"radio0","values":"{\"disabled\":0"}}
My last post: Split string by "\" Node.js
anyone can help?
is this you wanted?
var str =' {"config":"wireless","section":"radio0","values":"{\"disabled\":0"}';
console.log(str.replace(/\\/g,''));
Your object should be like you said in your last comment {"config":"wireless","section":"radio0","values":"{\"disabled\":0}"} then:
var jsonstring = "{"config":"wireless","section":"radio0","values":"{\"disabled\":0}"}";
var escapedJsonstring = jsonstring.split('\\').join('');
var json = JSON.parse(escapedJsonstring);
json.parsedValues = JSON.parse(json.values);
console.log(json);
Finally you have parsed object in json variable. The main idea is that the values attribute has also string value and not object value. So you need to parse it again as JSON. Result of this parsing is stored in json.parsedValues, but you can rewrite the values string with object using this: json.values = JSON.parse(json.values);
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));
});
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 );
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 !== ',');