This question already has answers here:
Convert JSON string to Javascript array [duplicate]
(4 answers)
Closed 5 years ago.
I have an array of geodata stored as a string, and need to turn into into a array of numbers.
var input = "[34.1103897,-118.0398531]"
var output = [34.1103897,-118.0398531]
Not sure the best way to do this. Any tips/ suggestions appreciated!
The easiest way to convert an array of that format is to use JSON.parse.
Simply:
var input = "[34.1103897,-118.0398531]";
var output = JSON.parse(input);
Assuming the data is always formatted with no whitespace, you could simply remove the first and last characters, and split on ',':
var input = '[34.1303897,-118.0398591]';
var output = input.slice(1, -1).split(',').map(parseFloat);
Alternatively, that syntax is technically valid JSON syntax, so you could just:
var input = '[34.1303897,-118.0398591]';
var output = JSON.parse(input);
However, this could be dangerous depending on where the data comes from.
JSON.parse is the obvious choice, but there is also manual parsing with a regular expression (the following assumes you might also want to match a leading '+'):
var input = "[34.1103897,-118.0398531]"
var output = (input.match(/[+-]?[\d\.]+/g) || []).map(Number);
console.log(output)
You might consider validating the input or the resulting output regardless of the method chosen to convert it to an array.
Related
This question already has answers here:
Parsing string as JSON with single quotes?
(10 answers)
Closed 2 years ago.
I am having a variable which stores a string like this
var colorArr="['#3f67c5', '#cb4728', '#f19d39', '#459331', '#984830', '#8C2094']"
I am trying to convert this string into an array by
var result = JSON.parse(colorArr)
But I keep on getting the following error
"SyntaxError: Unexpected token ' in JSON at position 1
Is there a way by which I can convert this string into a proper array?
Thanks in advance
Use single quotes and put double quotes inside of it
var colorArr= '["#3f67c5", "#cb4728", "#f19d39", "#459331", "#984830", "#8C2094"]';
var result = JSON.parse(colorArr)
console.log(result)
You can use regex to replace and split.
let colorArr="['#3f67c5', '#cb4728', '#f19d39', '#459331', '#984830', '#8C2094']";
let myArray = colorArr.replace(/'/g,'"')
console.log(JSON.parse(myArray))
try like this
var colorArr='["#3f67c5", "#cb4728", "#f19d39", "#459331", "#984830", "#8C2094"]';
JSON.parse(colorArr)
This question already has answers here:
How to grab substring before a specified character in JavaScript?
(12 answers)
Closed 6 years ago.
I am attempting to take the city out of a city, state string. For instance, "Portland, OR" would need to equal "Portland". How can I use Javascript or a regular expression to do this?
var myString = "Portland, OR";
I want to extract everything up to the comma but not including the comma.
var city = "Portland, OR".split(",")[0];
With regex:
var regex = /^[^,]+/;
var city = regex.exec("Portland, OR");
This is the regex version
var result = myString.match(/^[^,]+/)
UPDATE
This one always returns a value without error
var result = String(myString || "").match(/^[^,]*/)[0]
This question already has answers here:
Call a function if a string contains any items in an array
(3 answers)
Closed 8 years ago.
I have a string in my JavaScript code (plain JavaScript, no jQuery or any other libs involved). And also I have an array which contains characters to be found in a string. I need to check if string contains any of those characters. Of course, it could be done with temporary variable like found and array elements iteration.
But is there any way to write nice and compact code? Just in case, I use ES5 (IE9+).
I want to achieve something like
var str = "Here is the string",
chars = ['z','g'];
if (str.containsAnyOf(chars)) {
...
}
What is the best way to write that piece of code?
You can use Array.prototype.some, like this
if (chars.some(function(c) { return str.indexOf(c) !== -1; })) {
// Atleast one of the characters is present
};
Consider using regular expression:
var str = "Here is the string",
chars = ['z','g'];
// constructs the following regexp: /[zg]/
if (new RegExp("[" + chars.join('') + "]").test(str)) {
alert("Contains!");
}
This question already has answers here:
Find and get only number in string
(4 answers)
Closed 8 years ago.
I have the following string
/Date(1317772800000)/
I want to use a Javascript regular expression to extract the numerical portion of it
1317772800000
How is this possible?
That should be it
var numPart = "/Date(1317772800000)/".match(/(\d+)/)[1];
No need for regex. Use .substring() function. In this case try:
var whatever = "/Date(1317772800000)/";
whatever = whatever.substring(6,whatever.length-2);
This'll do it for you: http://regex101.com/r/zR0wH4
var re = /\/Date\((\d{13})\)\//;
re.exec('/Date(1317772800000)/');
=> ["/Date(1317772800000)/", "1317772800000"]
If you don't care about matching the date portion of the string and just want extract the digits from any string, you can use this instead:
var re = /(\d+)/;
re.exec('/Date(1317772800000)/')
["1317772800000", "1317772800000"]
How can I split the following string?
var str = "test":"abc","test1":"hello,hi","test2":"hello,hi,there";
If I use str.split(",") then I won't be able to get strings which contain commas.
Whats the best way to split the above string?
I assume it's actually:
var str = '"test":"abc","test1":"hello,hi","test2":"hello,hi,there"';
because otherwise it wouldn't even be valid JavaScript.
If I had a string like this I would parse it as an incomplete JSON which it seems to be:
var obj = JSON.parse('{'+str+'}');
and then use is as a plain object:
alert(obj.test1); // says: hello,hi
See DEMO
Update 1: Looking at other answers I wonder whether it's only me who sees it as invalid JavaScript?
Update 2: Also, is it only me who sees it as a JSON without curly braces?
Though not clear with your input. Here is what I can suggest.
str.split('","');
and then append the double quotes to each string
str.split('","'); Difficult to say given the formatting
if Zed is right though you can do this (assuming the opening and closing {)
str = eval(str);
var test = str.test; // Returns abc
var test1 = str.test1; // returns hello,hi
//etc
That's a general problem in all languages: if the items you need contain the delimiter, it gets complicated.
The simplest way would be to make sure the delimiter is unique. If you can't do that, you will probably have to iterate over the quoted Strings manually, something like this:
var arr = [];
var result = text.match(/"([^"]*"/g);
for (i in result) {
arr.push(i);
}
Iterate once over the string and replace commas(,) following a (") and followed by a (") with a (%) or something not likely to find in your little strings. Then split by (%) or whatever you chose.