I have an array like this
var array = ["f","test"];
var string =array.toString();
excepted string var string ='f','test';
current value: f,test
You almost had it. Try this:
array.map(x => "'" + x + "'").toString();
Variable names like array and string are probably...akin to bad etiquitte, but I got'chu:
var anArray = [ "f", "test" ];
var theString = "'" + anArray.join("','") + "'";
Using ES6 with string interpolation and arrow function.
You can use join() or toString() to display each item separated by a comma
var array = ["f","test"];
console.log(array.map(x=>`'${x}'`).join(','))
console.log(array.map(x=>`'${x}'`).toString())
Let's use Map in JS
var result = ["f","test"].map(function(b) {
return "'" + b + "'";
});
console.log(result.toString());
1. using JavaScript Array.join() method : It will join all elements of an array into a string.
DEMO
var array = ["f","test"];
var res = "'"+array.join("','")+"'";
console.log(res);
2. using ES6 spread(...) operator : It allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.
DEMO
let array = ["f","test"];
function printString(a,b) {
var str = `'${a}','${b}'`;
return str;
}
var res = printString(...array);
console.log(res);
3. using Array.map() method with ES6 syntax - It creates a new array with the results of calling a provided function on every element in this array.
DEMO
var array = ["f","test"];
var str = array.map(item => "'" + item + "'").join();
console.log(str);
I believe you want your ouptut as a string and not as array and code to be written such that it is supported by all browser (no ES6). So I have tried to keep it as simple as possible:
var arrayTest = ["f","test"]
var str = arrayTest.map(function(obj) {return("'" + obj + "'")}).toString();
Related
I am having string with column names and trying to get value of matched element from the json object with key,value
var str=""Object Status","Reason","Date From","Date To","Object Number",";
I am having Json Object inside an array
dataResult.Objects[0]={OBJECT_NUMBER:123,OBJCET_STATUS:"NEW",DATE_FROM:"/Date(1587764199000)/",DATE_TO:"/Date(1619755200000)/",REASON:"FRESHCOPY"}
I am trying to loop through array and try to get matched element but I shoudl be expecting them in the same order as the string values are present.
for (var i = 0; i <= dataResult.Objects.length; i++) {
var item = dataResult.Objects[i - 1];
var val = '';
$.each(item, function (key, value) {
var columnCollection = str.replace(/ /g, "").toUpperCase();
var matchingKey = key.replace(/_/g, '');
if (columnCollection.includes(matchingKey)) {
val += '"' + value + '",';
}
});
}
I tried with the above code snippet but I am getting result like "123,NEW,"/Date(1587764199000)/","/Date(1619755200000)/",FRESHCOPY" but I want the data tobe in same order as string.
I am expecting the result should be "NEW,"FRESHCOPY","/Date(1587764199000)/","/Date(1619755200000)/",123"
Please let me know how can I achieve in the same order of string columns.
Wouldn't something like that work for you?
const str=`"Object Status","Reason","Date From","Date To","Object Number"`,
obj = {OBJECT_NUMBER:123,OBJECT_STATUS:"NEW",DATE_FROM:"/Date(1587764199000)/",DATE_TO:"/Date(1619755200000)/",REASON:"FRESHCOPY"},
result = str
.split(',')
.map(key =>
obj[key
.toUpperCase()
.replace(/\s/g, '_')
.replace(/"/g,'')
])
console.log(result)
.as-console-wrapper{min-height:100%;}
Instead of looping through dataResult.Objects, loop through the str list and get the corresponding object from dataResult.Objects
I am getting a set of arrays in string format which looks like
[49,16,135],[51,16,140],[50,18,150]
Now I need to save them in an array of arrays. I tried it like
let array = [];
let str = '[49,16,135],[51,16,140],[50,18,150]';
array = str.split('[]');
console.log(array);
but it is creating only one array including all string as an element while I need to have
array = [[49,16,135],[51,16,140],[50,18,150]]
Add array delimiters to each end of the string, then use JSON.parse:
const str = '[49,16,135],[51,16,140],[50,18,150]';
const json = '[' + str + ']';
const array = JSON.parse(json);
console.log(array);
You are splitting it incorrectly, in the example, it will only split of there is a [] in the string
You can create a valid JSON syntax and parse it instead like so,
let str = '[49,16,135],[51,16,140],[50,18,150]';
let array = JSON.parse(`[${str}]`);
console.log(array);
Another way you could achieve this is by using a Function constructor. This method allows you to "loosely" pass your array.
const strArr = "[49,16,135],[51,16,140],[50,18,150]",
arr = Function(`return [${strArr}]`)();
console.log(arr);
I Have a string like
[ "Basic, JavaScript, PHP, Scala" ]
How to convert it like
[ 'Basic', 'JavaScript', 'PHP', 'Scala' ]
code
function loadDataToGridChiefComplaint() {
var tHRNo = document.getElementById("lblpthrno").value;
var tOPDNo = document.getElementById("lblptopd").value;
var localKeyChief = tHRNo + '-' + tOPDNo + '-ChiefComplaint';
var a = localStorage.getItem(localKeyChief);
var Item = JSON.stringify(a); // it show like ["Basic, JavaScript, PHP, Scala"]
}
JSON.stringify() returns a String so your question is incorrect. Item is not an Array.
const Item = '["Basic, JavaScript, PHP, Scala"]';
Therefore you should not use it. Instead simply return the array a in your function:
function loadDataToGridChiefComplaint() {
var tHRNo = document.getElementById("lblpthrno").value;
var tOPDNo = document.getElementById("lblptopd").value;
var localKeyChief = tHRNo + '-' + tOPDNo + '-ChiefComplaint';
return localStorage.getItem(localKeyChief); // <-- no use of JSON.stringify()
}
This way loadDataToGridChiefComplaint() is the array ["Basic, JavaScript, PHP, Scala"], it has a single element of type String that you can access with the bracket notation Item[0]:
const Item = ["Basic, JavaScript, PHP, Scala"];
console.log(Item[0]);
So in order to convert the string Item[0] into an array, use the .split method:
String.split(separator)
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
MDN Web Docs
const Item = ["Basic, JavaScript, PHP, Scala"];
console.log(Item[0].split(', '));
If you can't modify this function you can use the opposite operation of JSON.stringify which is JSON.parse to convert the string back to an array:
const ItemString = '["Basic, JavaScript, PHP, Scala"]';
ItemArray = JSON.parse(ItemString);
And then use .split (like the previous example) to get the array of strings.
Try this :
var Item = ["Basic, JavaScript, PHP, Scala"];
// Do like this
var array = Item[0].split(', '); // Split with Comma and space(for trim whitespace)
// Or Like this
var array = Item[0].split(',').map(i => i.trim()) // Split with comma and use map to trim whitespace
console.log(array);
I have an array of character with commas separating them. I need to split an array but retain my comma inbetween each character.
See below for an example array:
var myArray = [a,,,b,c,d,,,]
There's a comma in there between the characters "a" and "b". I need to retain the comma when converting the array to a string.
The output string needs to resemble this:
a,bcd,
This is what i'm currently doing to retain the commas:
myArray.toString().replace(/,/g, "");
The Array's toString() method basically does a join(",") which is why you are getting the extra commas in your string.
Instead use join("") if you want to join the elements without the delimiter being added as part of the string
var myArray = ["a",",","b","c","d",",",]
document.body.innerText = myArray.join("");
How about you use :
var myArray = [a,,,b,c,d,,,];
var str = myArray.join();
This will give a string of array elements, preserving the commas.
if you want it to maintain the centre comma you should create your array as
var myArray = [a,",",b,c,d,",",];
this will then treat the middle comma in the set of 3 as a string containing that character rather than the array seperator
You could change your regex, to replace item,item for item item.
myArray.toString().replace(/([a-z,]),([a-z,])/g, "$1$2")
Basically you have a sparse array and want to extract only filled values and convert it to string ? Here is one, probably not the best, solution :
var myArray = ['a',',',',','b',',','c']
var resultArray = [];
for(var i = 0; i < myArray.length; i++){
if(myArray[i] !== ','){// allow 0, false, null values, but not undefined
resultArray.push(myArray[i]);
}
}
console.log(resultArray);
Working plnkr : http://plnkr.co/edit/55T6PGI9DuTlvy6k88hr?p=preview, check the console of your broswer.
If this is an actual array of strings and you wanted only those with actual values, you could use the filter() function to filter out any non-undefined ones :
// Your example array
var input = ['a',,,'b','c','d',,,];
// Remove any undefined elements
var output = input.filter(function(e){ return e; }); // yields ['a','b','c','d']
You could then use the join() function to create a string with your elements :
var result = output.join(); // yields "a,b,c,d"
Example Snippet
var input = ['a',,,'b','c','d',,,];
document.write('INPUT: ' + input + '<br />');
var output = input.filter(function(e){ return e; });
document.write('OUTPUT: ' + output);
I have a string that I want to split into an array. The string looks like this:
'O:BED,N:KET,OT,N:JAB,FA,O:RPT,'
The string can contain any number of objects eg
'O:BED,N:KET,OT,N:JAB,FA,O:RPT,X:BLA,GTO'
I want to split this string on the instance of \w: eg O:
So I'll end up with array like this:
['O:BED','N:KET, OT','N:JAB,FA','O:RPT']
I am using the following code:
var array = st.split(/^(\w:.+)(?=\w:)/g);
However I end up with array like this :
['','O:BED,N:KET,OT,N:JAB,FA,','O:RPT,']
It seems the regex is being greedy, what should I do to fix it?
Note I am using angularjs and eventually I want to end up with this :
var objs = [
{type:O,code: BED, suf: ''},
{type:N, code: KET, suf: OT},
{type:N, code: JAB, suf: FA},
{type:O, code: RPT, suf: ''}
]
It would be much easier if your string is formatted properly. But still we can achieve the task with extra effort. Hope the below code works for you.
var str = 'O:BED,N:KET,OT,N:JAB,FA,O:RPT,X:BLA,GTO';
var a = str.split(',');
var objs = [], obj, item, suf;
for(var i=0; i<a.length;){
item = a[i].split(':');
if(a[i+1] && a[i+1].indexOf(':') == -1){
suf = a[i+1];
i++;
}else{
suf = "";
}
obj = {
type: item[0],
code: item[1],
suf: suf
};
objs.push(obj);
i++;
}
console.log(objs);
You can use the RegExp.prototype.exec method to obtain successive matches instead of splitting the string with a delimiter:
var myStr = 'O:BED,N:KET,OT,N:JAB,FA,O:RPT,';
var myRe = /([^,:]+):([^,:]+)(?:,([^,:]+))??(?=,[^,:]+:|,?$)/g;
var m;
var result = [];
while ((m = myRe.exec(myStr)) !== null) {
result.push({type:m[1], code:m[2], suf:((m[3])?m[3]:'')});
}
console.log(result);
You want to do a string match and then iterate over that.
Full example inside AngularJS: http://jsfiddle.net/184cyspg/1/
var myString = 'O:BED,N:KET,OT,N:JAB,FA,O:RPT,';
$scope.myArray = [];
var objs = myString.match(/([A-Z])\:([A-Z]*)\,([A-Z]?)/g);
objs.forEach(function (entry) {
var obj = entry.replace(',', ':');
obj = obj.split(':');
$scope.myArray.push({type: obj[0], code: obj[1], suf: obj[2]});
});
I love regular expressions :)
This will match each object of your string, if you want to use the global flag and exec() through all the matches:
(\w):(\w+)(?:,((?!\w:)\w+))?
The only real trick is to only treat the next bit after the comma as the suffix to this one if it doesn't look like the type of the next.
Each match captures the groups:
type
code
suf
If you just want to split as you said, then the solution to your greedy problem is to tell it to split on commas which are followed by those matching objects, eg:
,(?=(\w):(\w+)(?:,((?!\w:)\w+))?)
The following does not solve your regex issue however is an alternative approach to introduce underscorejs to handle from simple to more complex operations. Although an overkill in this case;
// ie. input string = 'O:BED,N:KET,OT,N:JAB,FA,O:RPT,';
.controller('AppCtrl', [function() {
/**
* Split by comma then (chain) eval each (map)
* element that (if-else) contains '0:' is pushed
* into array as a new element, otherwise concat element
*
* :#replace hardcoded values with params
*
* #param String string - a string to split
* #param String prefix - prefix to determine start of new array element ie. '0:'
* #param String delimiter - delimiter to split string ie ','
* #return Array array of elements by prefix
*/
$scope.splitter = function(string) {
var a = [];
var tmp = "";
_.chain(string.split(','))
.map(function(element) {
if(element.indexOf('O:') >= 0) {
element += tmp;
a.push(element);
tmp = "";
} else {
tmp += element;
}
});
return a;
};
}]);
Output:
array: Array[2]
0: "O:BED"
1: "O:RPTN:KETOTN:JABFA"
length: 2
Updated: Just read your requirements on Objects. underscorejs allows chaining operations. For example, the code above could be tweaked to handle Objects, chained to .compact().object().value() to produce output as Object k:v pairs;
Hope this helps.