Convert string with commas to array - javascript

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 !== ',');

Related

Parse string having key=value pairs as JSON

My node app receives a series of strings in the format "a=x b=y c=z" (i.e. a string containing several space-separated key=value pairs).
What is the neatest way of converting such a string into a JSON object of the form {a: x, b: y, c: z}?
I'm betting that there's a one-line solution, but haven't managed to find it yet.
Thanks.
One way would be to replace the with a , and an = with a ::
var jsonStr = '{' + str.replace(/ /g, ', ').replace(/=/g, ': ') + '}';
Or if you need quotes around the keys and values:
var jsonStr2 = '{"' + str.replace(/ /g, '", "').replace(/=/g, '": "') + '"}';
JSON.parse() it if you need.
Sample output:
str: a=x b=y c=z
jsonStr: {a: x, b: y, c: z}
jsonStr2: {"a": "x", "b": "y", "c": "z"}
Building on John Bupit's excellent answer, I have made a couple of further enhancements to end up with the following (the string being parsed being in message):
var json = JSON.parse(('{"' + message.replace(/^\s+|\s+$/g,'').replace(/=(?=\s|$)/g, '="" ').replace(/\s+(?=([^"]*"[^"]*")*[^"]*$)/g, '", "').replace(/=/g, '": "') + '"}').replace(/""/g, '"'));
Basically the scheme is as follows:
First replace(): trim off any leading or trailing whitespace -- equivalent to trim()
Second replace(): add double quotes (empty string) for any value that is completely missing (e.g. key1= key2=val goes to key1="" key2=val).
Third replace(): replace each space (which acts as a delimiter) with ", ", but not where the space is within double quotes (i.e. part of a string value).
Fourth replace(): replace each = with ": "
Wrap the entire string up as follows: {"..."}
Finally, replace any double quotes "" created by the above steps (because the value string was already wrapped in quotes in message) with single quotes "
Even more finally, run JSON.parse() over the result.
The above scheme should cope with missing values, with some values being quoted and some unquoted, and with spaces within value strings, e.g. something like a= b="x" c="y y" d=z.
Assuming that you don't get nested objects in that format :
var sample = 'a=x b=y c=z';
var newobj = {};
sample.split(' ').forEach(function (value) {
var keypair = value.split('=');
newobj[keypair[0]] = keypair[1];
});
console.dir(newobj);
What this does is split on every white-space and push to an array, and the array is looped and each item in array is split again to get each key-value pair which is assigned to the newobj.
Here's a simple function that will do the trick
function stringToObj (string) {
var obj = {};
var stringArray = string.split(' ');
for(var i = 0; i < stringArray.length; i++){
var kvp = stringArray[i].split('=');
if(kvp[1]){
obj[kvp[0]] = kvp[1]
}
}
return obj;
}
newstr = ""
for kvp in #value.split(" ")
newstr += kvp.replace(/=/,'":"').replace(/^/, '"').replace(/$/, '"').replace(/\"\"/,'" "')
newstr = newstr.replace(/\"\"/g, '","')
jsn = JSON.parse('{' + newstr + '}')
I created a simple online tool for similar need: https://superal.github.io/online-tools/
Use cases:
To transfer key:value pairs copied from chrome network requests(form data or query string parameters) or postman headers key-value(in bulk edit style) to json format.
For example:
key:value pairs
platform:2
limit:10
start_time:1521561600
end_time:1522080000
offset:0
to json format
{
"platform": "2",
"limit": "10",
"start_time": "1521561600",
"end_time": "1522080000",
"offset": "0"
}
It can be parsed (converted to json) using the help of this npm athena-struct-parser package.
For more information about the package -- https://www.npmjs.com/package/athena-struct-parser
Sample Nodejs Code
var parseStruct =require('athena-struct-parser') ;
var str = '{description=Check the Primary key count of TXN_EVENT table in Oracle, datastore_order=1, zone=yellow, aggregation_type=count, updatedcount=0, updatedat=[2021-06-09T02:03:20.243Z]}'
var parseObj = parseStruct(str)
console.log(parseObj);
Sample string with key=value format taken
{description=Check the Primary key count of TXN_EVENT table in Oracle, datastore_order=1, zone=yellow, aggregation_type=count, updatedcount=0, updatedat=[2021-06-09T02:03:20.243Z]}
Result Parsed output
{
description: 'Check the Primary key count of TXN_EVENT table in Oracle',
datastore_order: '1',
zone: 'yellow',
aggregation_type: 'count',
updatedcount: '0',
updatedat: [ '2021-06-09T02:03:20.004Z' ]
}
I would use an approach leveraging URLSearchParams and Object.fromEntries() like so:
const input = "a=x b=y c=z";
const queryString = input.replaceAll(" ", "&");
const query = new URLSearchParams(queryString);
const output = Object.fromEntries(query);
console.log(output);
Breakdown:
The URLSearchParams constructor takes a string of key-value pairs joined by "&" as it's argument, and parses it into a URLSearchParams object instance. So to use this, the space separators in the original input need to be replaced with a "&" character.
The URLSearchParams instance we have after parsing is an iterable, so we can transform it into a plain Object with Object.fromEntries().
It's not too bad as a one-liner either:
const input = "a=x b=y c=z";
const output = Object.fromEntries(new URLSearchParams(input.replaceAll(" ", "&")));

Separate value from string using javascript

I have a string in which every value is between [] and it has a . at the end. How can I separate all values from the string?
This is the example string:
[value01][value02 ][value03 ]. [value04 ]
//want something like this
v1 = value01;
v2 = value02;
v3 = value03;
v4 = value04
The number of values is not constant. How can I get all values separately from this string?
Use regular expressions to specify multiple separators. Please check the following posts:
How do I split a string with multiple separators in javascript?
Split a string based on multiple delimiters
var str = "[value01][value02 ][value03 ]. [value04 ]"
var arr = str.split(/[\[\]\.\s]+/);
arr.shift(); arr.pop(); //discard the first and last "" elements
console.log( arr ); //output: ["value01", "value02", "value03", "value04"]
JS FIDDLE DEMO
How This Works
.split(/[\[\]\.\s]+/) splits the string at points where it finds one or more of the following characters: [] .. Now, since these characters are also found at the beginning and end of the string, .shift() discards the first element, and .pop() discards the last element, both of which are empty strings. However, your may want to use .filter() and your can replace lines 2 and 3 with:
var arr = str.split(/[\[\]\.\s]+/).filter(function(elem) { return elem.length > 0; });
Now you can use jQuery/JS to iterate through the values:
$.each( arr, function(i,v) {
console.log( v ); // outputs the i'th value;
});
And arr.length will give you the number of elements you have.
If you want to get the characters between "[" and "]" and the data is regular and always has the pattern:
'[chars][chars]...[chars]'
then you can get the chars using match to get sequences of characters that aren't "[" or "]":
var values = '[value01][value02 ][value03 ][value04 ]'.match(/[^\[\]]+/g)
which returns an array, so values is:
["value01", "value02 ", "value03 ", "value04 "]
Match is very widely supported, so no cross browser issues.
Here's a fiddle: http://jsfiddle.net/5xVLQ/
Regex patern: /(\w)+/ig
Matches all words using \w (alphanumeric combos). Whitespace, brackets, dots, square brackets are all non-matching, so they don't get returned.
What I do is create a object to hold results in key/value pairs such as v1:'value01'. You can iterate through this object, or you can access the values directly using objRes.v1
var str = '[value01][value02 ][value03 ]. [value04 ]';
var myRe = /(\w)+/ig;
var res;
var objRes = {};
var i=1;
while ( ( res = myRe.exec(str) ) != null )
{
objRes['v'+i] = res[0];
i++;
}
console.log(objRes);

How to use Javascript slice to extract first and last letter of a string?

How to use JavaScript slice to extract the first and last letter of a string?
Eg: "Hello World"
I need the result as "dH".
Following is my jsfiddle :
http://jsfiddle.net/vSAs8/
Here's the cleanest solution :
var output = input.slice(-1)+input[0];
If you want more slice, there's also
var output = input.slice(-1)+input.slice(0,1);
And here are alternate fun (and less efficient) solutions :
var output = input.replace(/^(.).*(.)$/,'$2$1');
or
var output = input.match(/^.|.$/g).reverse().join('');
Substr works as well:
alert(test.substr(-1,1) + test.substr(0,1));
a.charAt(a.length-1) + a.charAt(0)
var str = " Virat Kohali "
var get_string_label = function(str){
str = str.split(" ");
str = str.filter(res=>res.length>0);
str = str.map(function(res){
return res[0].toUpperCase();
});
str = str.join("");
return str;
};
console.log(get_string_label(str));
str.split(" "); method splits a String object into an array of strings by separating the string into substrings, where it will find space in string.
then str.filter(res=>res.length>0) will filter out string having zero length (for "virat kohali" string you will get empty sub-string)
after that using map function you can fetch your first letter

How to Convert Array-like String to Array

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 );

Javascript split only once and ignore the rest

I am parsing some key value pairs that are separated by colons. The problem I am having is that in the value section there are colons that I want to ignore but the split function is picking them up anyway.
sample:
Name: my name
description: this string is not escaped: i hate these colons
date: a date
On the individual lines I tried this line.split(/:/, 1) but it only matched the value part of the data. Next I tried line.split(/:/, 2) but that gave me ['description', 'this string is not escaped'] and I need the whole string.
Thanks for the help!
a = line.split(/:/);
key = a.shift();
val = a.join(':');
Use the greedy operator (?) to only split the first instance.
line.split(/: (.+)?/, 2);
If you prefer an alternative to regexp consider this:
var split = line.split(':');
var key = split[0];
var val = split.slice(1).join(":");
Reference: split, slice, join.
Slightly more elegant:
a = line.match(/(.*?):(.*)/);
key = a[1];
val = a[2];
May be this approach will be the best for such purpose:
var a = line.match(/([^:\s]+)\s*:\s*(.*)/);
var key = a[1];
var val = a[2];
So, you can use tabulations in your config/data files of such structure and also not worry about spaces before or after your name-value delimiter ':'.
Or you can use primitive and fast string functions indexOf and substr to reach your goal in, I think, the fastest way (by CPU and RAM)
for ( ... line ... ) {
var delimPos = line.indexOf(':');
if (delimPos <= 0) {
continue; // Something wrong with this "line"
}
var key = line.substr(0, delimPos).trim();
var val = line.substr(delimPos + 1).trim();
// Do all you need with this key: val
}
Split string in two at first occurrence
To split a string with multiple i.e. columns : only at the first column occurrence
use Positive Lookbehind (?<=)
const a = "Description: this: is: nice";
const b = "Name: My Name";
console.log(a.split(/(?<=^[^:]*):/)); // ["Description", " this: is: nice"]
console.log(b.split(/(?<=^[^:]*):/)); // ["Name", " My Name"]
it basically consumes from Start of string ^ everything that is not a column [^:] zero or more times *. Once the positive lookbehind is done, finally matches the column :.
If you additionally want to remove one or more whitespaces following the column,
use /(?<=^[^:]*): */
Explanation on Regex101.com
function splitOnce(str, sep) {
const idx = str.indexOf(sep);
return [str.slice(0, idx), str.slice(idx+1)];
}
splitOnce("description: this string is not escaped: i hate these colons", ":")

Categories

Resources