Convert comma separated string to a JavaScript array - javascript

I have this string:
"'California',51.2154,-95.2135464,'data'"
I want to convert it into a JavaScript array like this:
var data = ['California',51.2154,-95.2135464,'data'];
How do I do this?
I don't have jQuery. And I don't want to use jQuery.

Try:
var initialString = "'California',51.2154,-95.2135464,'data'";
var dataArray = initialString .split(",");

Use the split function which is available for strings and convert the numbers to actual numbers, not strings.
var ar = "'California',51.2154,-95.2135464,'data'".split(",");
for (var i = ar.length; i--;) {
var tmp = parseFloat(ar[i]);
ar[i] = (!isNaN(tmp)) ? tmp : ar[i].replace(/['"]/g, "");
}
console.log(ar)
Beware, this will fail if your string contains arrays/objects.

Since you format almost conforms to JSON syntax you could do the following :
var dataArray = JSON.parse ('[' + initialString.replace (/'/g, '"') + ']');
That is add '[' and ']' characters to be beginning and end and replace all "'' characters with '"'. than perform a JSON parse.

Related

Converting associative array string to array

I've been trying to convert an associative array string but I can't seem to make it work.
I've tried the code below but it is not working.
var string = "{'custom_text_record': 'Text Here', 'fill_record': '0'}";
var s_obj = JSON.parse(string) ;
alert(s_obj['custom_text_record']);
You need to basically get JSON format from the associative array string,
The JSON format should be "{'custom_text_record': 'TextHere','fill_record':'0'}" before we use JSON parse function
Please try this.
var string = '{"custom_text_record": "Text Here", "fill_record": "0"}';
var jsonStrig = '{';
var items = string.split(',');
for (var i = 0; i < items.length; i++) {
var current = items[i].split(':');
jsonStrig += '"' + current[0].replace(/{|'|"|}|\s/g, '') + '":"' +
current[1].replace(/{|'|"|}|\s/g, '') + '",';
}
jsonStrig = jsonStrig.substr(0, jsonStrig.length - 1);
jsonStrig += '}';
var s_obj = JSON.parse(jsonStrig);
console.log(s_obj['custom_text_record']);
Regex might be used to filter the single quote, double quote, and bracket, spaces which can appear in the associative array string.
I think we can convert any type of associative array string like '{ key : value }' style into the correct JSON format and finally get an array in this way.
I hope this would be helpful.

Convert a string of array into array javascript

In my code i am reading a hidden input value which is actually a javascript array object
<input type="hidden" id="id_num" value="{{array_values}}">
But when i taking it using jquery ($('#id_num").val()) its a string of array,
"['item1','item2','item3']"
so i can not iterate it.How should i convert into javascript array object, so that i can iterate through items in the array?
You can use JSON.parse but first you need to replace all ' with " as ' are invalid delimitters in JSON strings.
var str = "['item1','item2','item3']";
str = str.replace(/'/g, '"');
var arr = JSON.parse(str);
console.log(arr);
Another approach:
Using slice and split like this:
var str = "['item1','item2','item3']";
var arr = str.slice(1, -1) // remove [ and ]
.split(',') // this could cause trouble if the strings contain commas
.map(s => s.slice(1, -1)); // remove ' and '
console.log(arr);
You can use eval command to get values from string;
eval("[0,1,2]")
will return;
[0,1,2]
more details here
Though it should be noted, if this string value comes from users, they might inject code that would cause an issue for your structure, if this string value comes only from your logic, than it is alright to utilize eval
var arr = "['item1','item2','item3']";
var res = arr.replace(/'/g, '"')
console.log(JSON.parse(res));
A possible way of solving this:
First, substr it to remove the [..]s.
Next, remove internal quotes, since we would be getting extra when we string.split
Finally, split with ,.
let mystring = "['item1','item2','item3']";
let arr = mystring.substr(1, mystring.length - 2)
.replace(/'/g, "")
.split(",")
console.log(arr)

Javascript: String of text to array of characters

I'm trying to change a huge string into the array of chars. In other languages there is .toCharArray(). I've used split to take dots, commas an spaces from the string and make string array, but I get only separated words and don't know how to make from them a char array. or how to add another regular expression to separate word? my main goal is something else, but I need this one first. thanks
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.toLowerCase();
str = str.split(/[ ,.]+/);
You can use String#replace with regex and String#split.
arrChar = str.replace(/[', ]/g,"").split('');
Demo:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
var arrChar = str.replace(/[', ]/g,"").split('');
document.body.innerHTML = '<pre>' + JSON.stringify(arrChar, 0, 4) + '</pre>';
Add character in [] which you want to remove from string.
This will do:
var strAr = str.replace(/ /g,' ').toLowerCase().split("")
First you have to replace the , and . then you can split it:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
var strarr = str.replace(/[\s,.]+/g, "").split("");
document.querySelector('pre').innerHTML = JSON.stringify(strarr, 0, 4)
<pre></pre>
var charArray[];
for(var i = 0; i < str.length; i++) {
charArray.push(str.charAt(i));
}
Alternatively, you can simply use:
var charArray = str.split("");
I'm trying to change a huge string into the array of chars.
This will do
str = str.toLowerCase().split("");
The split() method is used to split a string into an array of
substrings, and returns the new array.
Tip: If an empty string ("") is used as the separator, the string is
split between each character.
Note: The split() method does not change the original string.
Please read the link:
http://www.w3schools.com/jsref/jsref_split.asp
You may do it like this
var coolString,
charArray,
charArrayWithoutSpecials,
output;
coolString = "If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
// does the magic, uses string as an array to slice
charArray = Array.prototype.slice.call(coolString);
// let's do this w/o specials
charArrayWithoutSpecials = Array.prototype.slice.call(coolString.replace(/[', ]/g,""))
// printing it here
output = "<b>With special chars:</b> " + JSON.stringify(charArray);
output += "<br/><br/>";
output += "<b>With special chars:</b> " + JSON.stringify(charArrayWithoutSpecials)
document.write(output);
another way would be
[].slice.call(coolString)
I guess this is what you are looking for. Ignoring all symbols and spaces and adding all characters in to an array with lower case.
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.replace(/\W/g, '').toLowerCase().split("");
alert(str);

split words,numbers from string and put it as 2D array in JavaScript

I have an string like'[[br,1,4,12],[f,3]]'. I want to split as strings and integers and put it into array like the string [['br',1,4,12],[f,3]].string maybe like '[]' or '[[cl,2]]',ect...but the words only,br,cl,fand i. How does get the array. Any idea for this problem?
Thanks
You can do conversion that you wanted by using RegEx :
Get your string
var str = '[[br,1,4,12],[f,3]]';
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
console.log(str);
//Outputs :
[["brd",1,4,12],["f",3]] // It is still just a string
If you wanted to convert it to object, you might use this :
var str = '[[br,1,4,12],[f,3]]';
function toJSObject(str){
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
return (JSON.parse(str))
}
var obj = toJSObject(str);

How do I split this string with JavaScript?

Javascript:
var string = '(37.961523, -79.40918)';
//remove brackets: replace or regex? + remove whitespaces
array = string.split(',');
var split_1 = array[0];
var split_2 = array[1];
Output:
var split_1 = '37.961523';
var split_2 = '-79.40918';
Should I just use string.replace('(', '').replace(')', '').replace(/\s/g, ''); or RegEx?
Use
string.slice(1, -1).split(", ");
You can use a regex to extract both numbers at once.
var string = '(37.961523, -79.40918)';
var matches = string.match(/-?\d*\.\d*/g);
You would probably like to use regular expressions in a case like this:
str.match(/-?\d+(\.\d+)?/g); // [ '37.961523', '-79.40918' ]
EDIT Fixed to address issue pointed out in comment below
Here is another approach:
If the () were [] you would have valid JSON. So what you could do is either change the code that is generating the coordinates to produce [] instead of (), or replace them with:
str = str.replace('(', '[').replace(')', ']')
Then you can use JSON.parse (also available as external library) to create an array containing these coordinates, already parsed as numbers:
var coordinates = JSON.parse(str);

Categories