Converting an array in curly braces to a square bracketed array - javascript

I've inherited a database that stores an array of strings in the following format:
{"First","Second","Third","Fourth"}
This is output as an ordered list in the application. We're replacing the front-end mobile app at the moment (ionic / angular) and want to do an ngFor over this array. In the first iteration, we did a quick and dirty replace on the curly brackets and then split the string on "," but would like to use a better method.
What is the best method for treating this type of string as an array?

You could do a string replacement of braces to brackets:
str.replace(/{(.*)}/, '[$1]')
This particular string could then be parsed as an array (via JSON.parse).

If you're looking to do the parsing to an array on the front end, would this work?:
const oldStyle = '{"First","Second","Third","Fourth"}'
const parseOldStyleToArray = input => input
.replace(/[\{\}]/g, '')
.split(',')
.map(item => item.replace(/\"/g, ''))
const result = parseOldStyleToArray(oldStyle)
console.dir(result)

Another way to do more widest replacement by key:value mapping.
str = '{"First","Second","Third","Fourth"}';
mapping = {
'{': '[',
'}': ']'
}
result = str.replace(/[{}]/g, m => mapping[m]);
console.log(result);

Related

How to check if a string includes a template literal in javascript?

I have tried checking this using the function str.includes('${') as a trivial solution but I am not receiving the correct output. I am also getting back the strings that do not include it.
An example string that would satisfy this condition is: 'My name is ${customer.Name} '
You can probably use Regex to find it. If you are just looking to see if a string just has a template literal in it you could do something like the following:
const str = 'My name is ${customer.Name} '
const regex = /\${(.*?)\}/g
const hasTemplateLiteral = (str) => str.search(regex) > -1
console.log(hasTemplateLiteral(str))
You can check the javascript regular expressions functions here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#using_regular_expressions_in_javascript. /\${(.*?)\}/g will check for the ${} with anything in between the brackets and return the index if it is found or return -1 if not found. You can test the regex here https://regexr.com/
Note this will only work if the template literal is actually in string format like your example above. If your template literal is in backticks then it will actually contain the variable. Then it won't work and you would then have to check if the string includes the variable that is in your template literal like so:
const customer = {Name: 'bob'}
const str = `My name is ${customer.Name}`
const regex = /\${(.*?)\}/g
const hasIncludedVariable = (str, v) => str.includes(v)
console.log(hasIncludedVariable(str, customer.Name))

Comma separated string into multiple arrays separated by comma using javascript

How to convert comma separated string into multiple array strings separated by comma
var data = "34,2,76",
result = data.split(',').map(s => s.split(',')).slice(0);
console.log(result);
The result is [ ["34"], ["2"], ["76"] ].
How to get the output exactly as below as a string?
[ myarray.values[34], myarray.values[2], myarray.values[76] ]
Notice that I do not have double quotes and each array has a name. Also we do not know how many comma separated values will be passed.
I use react and some ES6 cool way will be even better.
You can split on the comma and then map each part using template literal interpolation and then join on the comma, prepending a opening square bracket and appending a closing square bracket to the result.
const data = "34,2,76";
const res = '[' + data.split(',').map(x => `myarray.values[${x}]`).join(',') + ']';
console.log(res);

Inserting array elements in parentheses

I got a sorted 2D array [[0,1],[1,1],[1,2],[2,3]] in javascript.
I have to convert this array into a string with each element separated by a pair of parentheses, eg. the above array should return a string as "(0,1)(1,1)(1,2)(2,3)"
i tried converting the array into string using join and tried inserting the parentheses at the begining and the end using traditional approach..
var elem = elements.join(')(').split();
elem.unshift('(');
elem.push(')');
console.log(elem.join());
but output i'm getting is a string as "(,0,0)(1,1)(1,1)(2,3,)"
how to remove the unwanted commas in between?
console.log([[0,1],[1,1],[1,2],[2,3]].map(a => `(${a})`).join(''));
//or
console.log([[0,1],[1,1],[1,2],[2,3]].reduce((result, item) => result + `(${item})`, ''));

How to convert an array like string to array in node.js?

Actually I'm getting the arraylist from android device in node.js . But as it's in string form so I wanna convert it into an array . For that I've referred a lot of similar questions in SO but none of them were helpful . I also tried to use JSON.parse() but it was not helpful.
I'm getting societyList in form '[Art, Photography, Writing]'.Thus how to convert this format to an array?
Code:
var soc_arr=JSON.parse(data.societyList)
console.log(soc_arr.length)
use something like this
var array = arrayList.replace(/^\[|\]$/g, "").split(", ");
UPDATE:
After #drinchev suggestion regex used.
regex matches char starts with '[' and ends with ']'
This string is not valid JSON since it does not use the "" to indicate a string.
The best way would be to parse it yourself using a method like below:
let data = '[test1, test2, test3]';
let parts = data
.trim() // trim the initial data!
.substr(1,data.length-2) // remove the brackets from string
.split(',') // plit the string using the seperator ','
.map(e=>e.trim()) // trim the results to remove spaces at start and end
console.log(parts);
RegExp.match() maybe
console.log('[Art, Photography, Writing]'.match(/\w+/g))
So match() applies on any string and will split it into array elements.
Use replace and split. In addition, use trim() to remove the trailing and leading whitespaces from the array element.
var str = '[Art, Photography, Writing]';
var JSONData = str.replace('[','').replace(']','').split(',').map(x => x.trim());
console.log(JSONData);

How could one split a comma delimited string while ignoring the commas which are in braces?

I have a string which represents the attributes of a function:
str = "'MyCommunities', null, {'viewAllLink':'https://cpkornferrybruceapidev.azurewebsites.net', 'clientId':'078c49af-bb40-44c3-a685-539a84cc5de7', 'subscriptionId':'64fc6f58-2a67-472b-b57f-f0f5441e7992'}"
There are 3 attributes: My Communities, null, {...}
I would like to split the string into array containing these 3 values but without splitting the object literal.
I believe I need to construct a regular expression which would allow me to str.split(//) however I am not able to get the 3 attributes which I need.
Any help would be appreciated.
If be sure the string doesn't have extra ' in the value of each element, I think one quick way is treat it as one JSON string, then pull out the element you need.
The codes are like below:
let str = "'MyCommunities', null, {'viewAllLink':'https://cpkornferrybruceapidev.azurewebsites.net', 'clientId':'078c49af-bb40-44c3-a685-539a84cc5de7', 'subscriptionId':'64fc6f58-2a67-472b-b57f-f0f5441e7992'}"
console.log(JSON.parse('[' + str.replace(/'/g, '"') +']'))
If you don't have nested braces and if comma is always before {, then you can do this:
var re = /(\{[^}]+\})/;
var result = [];
str.split(re).forEach(function(part) {
if (part.match(re) {
result.push(part);
} else {
var parts = part.split(',').map((x) => x.trim()).filter(Boolean);
result = result.concat(parts);
}
});
if you have something before braces or if braces are nested you will need more compicated parser.
My first suggestion would be to find a different way to get the string formatted coming into your system. If that is not feasible, you can do the following regex (note: it is super fragile):
/\,(?![^{]*})/
and get the groupings like so:
list = str.split(/\,(?![^{]*})/)
I would use the second limit parameter of split() (docs) to stop cutting before the object literal:
var str = "'MyCommunities', null, {'viewAllLink':'https://cpkornferrybruceapidev.azurewebsites.net', 'clientId':'078c49af-bb40-44c3-a685-539a84cc5de7', 'subscriptionId':'64fc6f58-2a67-472b-b57f-f0f5441e7992'}";
console.log(str.split(', ', 3));

Categories