Convert to String Format - javascript

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

Related

Loading string to array of array

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

javascript:array to string in javascript:enclosed with single quotes

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

Allowing commas to follow through when converting array to string

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

Regex extract contents

So, I have the following data here:
{"screenName":"fubars","msgHash":"C5STUYqhjzNiP6LLVbPlTF3zYLVYXHrm","imgURL":null,"userColor":"#00a4a0","messageTime":"2:50 PM","messageDate":1442256635621,"accountType":"m","accountTypeID":"z2ZkdXqck-JO45hqXVXH","isModerator":"","badges":""
I've written some regex to extract strings, but if I search for example "screenName" it gets the "fubars" part and the rest of the string, I only want the "fubars" part...
code:
function extractSummary(iCalContent, what) {
eval("var rxm = /\""+what+"\": \"(.*)\"/g");
console.log(rxm);
setTimeout(function(){},1500);
var arr = rxm.exec(iCalContent);
return arr[1];
}
If you have some data in the form of a JSON string, you can use JSON.parse to convert it into a JSON object. You can then use dot or index property getters.
var jsonString = '{"screenName":"fubars","msgHash":"C5STUYqhjzNiP6LLVbPlTF3zYLVYXHrm"}';
var jsonObject = JSON.parse(jsonString);
console.log(jsonObject.screenName);
console.log(jsonObject['screenName']);
There's no need to use regexes here.

How do I extract JSON objects from a string and add them to an array?

I want to extract all JSON objects from a string randomly containing them and add them to an array.
Sample string:
"I was with {"name":"John"}{"name":"Anne"}{"name":"Daniel"} yesterday"`
how can i extract the JSON objects from this sample string?
One approach to this is to use the str.search(regexp) function to find all parts of it that fulfill the JSON regex found here. So you could write a function that searches over the string for regexp matches.
To actually extract the object from the string you could use these two functions for the regex and then loop over the string until all objects have been found.
var match = str.match(regex);
var firstIndex = str.indexOf(match[0]);
var lastIndex = str.lastIndexOf(match[match.length-1]);
var JSONobjects = [];
while( str.match(regex){
//extract the wanted part.
jsonObject = substr(str.indexOf(match[0],str.lastIndexOf(match[match.length1-]));
//remove the already found json part from the string and continue
str.splice(str.indexOf(match[0],str.indexOf(match[0] + jsonObject.length());
//parse the JSON object and add it to an array.
JSONobjects.push(JSON.parse(jsonObject));
}
var a = JSON.parse('{"name":"John"}');
a ==> Object {name: "John"}
var b = [];
b.push(a);

Categories