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);
Related
i have this string => someRandomText&ab_channel=thisPartCanChange and i want to delete all from & (inclusive) to the end [this part: &ab_channel=thisPartCanChange].
How can i do this?
You van try something like:
console.log("someRandomText&ab_channel=thisPartCanChange".split("&")[0])
const yourString = 'SomeRandomText&ab_channel=thisPartCanChange'
console.log(yourString.split('&ab_channel')[0])
I would do a regex replacement on &.*$ and replace with empty string.
var inputs = ["someRandomText&ab_channel=thisPartCanChange", "someRandomText"];
inputs.forEach(x => console.log(x.replace(/&.*$/, "")));
Note that the above approach is robust with regard to strings which don't even have a & component.
You can use substring which extract the characters between two specified index without changing the original string
const yourString = 'someRandomText&ab_channel=thisPartCanChange';
const newStr = yourString.substring(0, yourString.indexOf('&'));
console.log(newStr)
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));
I have this following javascript variable.
var data = "ashley, andy, juana"
i Want the above data to look like this.
var data = "Sports_ashley, Sports_andy, Sports_juana"
It should be dynamic in nature. any number of commas can be present in this variable.
Can someone let me an easy way to achieve this please.
Using .replace should work to add sports before each comma. Below I have included an example.
var data = data.replace(/,/g , ", Sports_");
In that example using RegExp with g flag will replace all commas with Sports, instead of just the first occurrence.
Then at the end you should just be able to append Sports to the end like so.
data = "Sports_" + data;
Probably an overkill, but here is a generic solution
function sportify(data) {
return data
.split(/\s*,\s*/g) //splits the string on any coma and also takes out the surrounding spaces
.map(function(name) { return "Sports_" + name } ) //each name chunk gets "Sport_" prepended to the end
.join(", "); //combine them back together
}
console.log(sportify("ashley, andy, juana"));
console.log(sportify("ashley , andy, juana"));
String.replace()
Array.map()
Array.join()
EDIT: updated with the new version of the OP
Use a regex to replace all occurrences of a , or the beginning of the string using String#replace()
var input = "ashley, andy, juana"
var output = input.replace(/^|,\s*/g, "$&Sports_");
console.log(output);
I've got the following string:
str = "data1 data2 data3";
And I want to convert it to an array doing the following:
list = str.split(",");
But when I run this:
alert(list[1]);
…it does not retrieve "data2". And when I call this:
alert(data[0]);
¬it retrieves "data1, data2, data3".
Is there something wrong? I want to access the different words from the string by calling them from the number (0,1,2 - in this case) instead of all of them going to list[0]
The separator you are using in the split method is comma(,). But your input string does not have a comma, but it has spaces between words. So you need to split with space as the operator.
list = str.split(" ");
When separator is found, it is removed from the string and the substrings are returned in an array. If separator is not found, the array contains one element consisting of the entire string.
You are trying to split using "," as a separator. You will have to use:
list = str.split(" ");
It'll work that way ;)
I'm trying to split a huge string that uses "}, {" as it's separator.
If I use the following code will I get split it into it's own string?
var i;
var arr[];
while(str) {
arr[i] = str.split("/^}\,\s\{\/");
}
First, get rid of the while loop. Strings are immutable, so it won't change, so you'll have an infinite loop.
Then, you need to get rid of the quotation marks to use regex literal syntax and get rid of the ^ since that anchors the regex to the start of the string.
/},\s\{/
Or just don't use a regex at all if you can rely on that exact sequence of characters. Use a string delimiter instead.
"}, {"
Also, this is invalid syntax.
var arr[];
So you just do the split once, and you'll end up with an Array of strings.
All in all, you want something like this.
var arr = str.split(/*your split expression*/)
var arr = str.split(/[\{\},\s]+/)
var s = 'Hello"}, {"World"}, {"From"}, {"Ohio';
var a = s.split('"}, {"');
alert(a);