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);
Related
I have an array of string which looks like this:
ErrStr = [
\\abc\def\ghi; ,
\\klm\nop\qrs;
]
So, this array of strings will be dynamic, so what I want to extract is only the abc and klm from this array.
This piece of code is what joins the strings after filtering from the data:
let errorArr = filteredError.map(a => a.ErrStr.split('\\\\', '')).join('')
I tried the above code, it cuts the \\ and replaces with , but I am not able to figure out how do I remove the 2nd and 3rd part of the string. Thanks in advance.
Backslash in an Escape character in Javascript and has special meaning. To literally use it you need to, well, escape it beforehand with another backslash
const str1 = "\a";
console.log(str1); // "a" Where's my backslash?
const str2 = "\\a";
console.log(str2); // "\a" Aha, here it is
Therefore, first make sure your array has Strings (which currently what you provided are not strings therefore it's an invalid JSON)
And use:
const arr = [
"\\\\abc\\def\\ghi;",
"\\\\klm\\nop\\qrs;",
];
const codes = arr.map(s => /(?<=^\\\\)[^\\]+/.exec(s)).flat()
console.log(codes); // ["abc", "klm"]
Overview example on Regex101.com
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})`, ''));
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);
I want to replace dot (.) in a string with empty string like this:
1.234 => 1234
However following regex makes it totally empty.
let x = "1.234";
let y = x.replace(/./g , "");
console.log(y);
However it works good when I replace comma (,) like this:
let p=x.replace(/,/g , "");
What's wrong here in first case i.e. replacing dot(.) by empty string? How it can be fixed?
I am using this in angular.
Try this:
let x: string = "1.234";
let y = x.replace(/\./g , "");
Dot . is a special character in Regex. If you need to replace the dot itself, you need to escape it by adding a backslash before it: \.
Read more about Regex special characters here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Use /[.]/g instead of simply /./g as . matches almost any character except whitespaces
console.log('3.14'.replace(/[.]/g, '')); // logs 314
An alternative way to do this(another post have already answered it with regex) is to use split which will create an array and then use join to join the elements of the array
let x = "1.234";
// splitting by dot(.) delimiter
// this will create an array of ["1","234"]
let y = x.split('.').join(''); // join will join the elements of the array
console.log(y)
I have an string like so
var user = "henry, bob , jack";
How can I make that into an array so I could call
user[0]
and so on.
The String.prototype.split method splits a string into an array of strings, using a delimiter character. You can split by comma, but then you might have some whitespace around your entries.
You can use the String.prototype.trim method to remove that whitespace. You can use Array.prototype.map to quickly trim every item in your array.
ES2015:
const users = user.split(',').map(u => u.trim());
ES5:
var users = user.split(',').map(function(u) { return u.trim(); });
Use the string's split method which splits the string by regular expression:
var user = "henry, bob , jack";
var pieces = user.split(/\s*,\s*/);
// pieces[0] will be 'henry', pieces[1] will be 'bob', and so on.
The regular expression \s*,\s* defines the separator, which consists of optional space before the comma (\s*), the comma and optional space after the comma.
You can use String.prototype.split() and Array.prototype.map() functions for getting an array. And String.prototype.trim() for removing unnecessary spaces.
var user = "henry, bob , jack";
user = user.split(',').map(e => e.trim());
document.write(user[0]);