Alternative eval() to execute the string - javascript

My array is A=['Apple','Peach','Orange']in Javascript, someone pass me the string like "A[1]" , how to convert the string "A[1]" to an executable item, so I can get 'Peach' as the result.
eval(A[1]) used to work but is not allowed here.

Using regex you can parse out the variable and the index, then grab them off the window object.
A=['Apple','Peach','Orange'];
let string = "A[1]";
let variable = string.match(/[^[]*/)[0];
let index = string.match(/\[(.*)\]/)[1];
console.log(window[variable][index]);

You could split by apostrophe and then filter out the odd array members:
var arrayString = "A=['Apple','Peach','Orange']"
var parsed = arrayString.split("'").filter(function(a, b){return b % 2});
console.log(parsed)

Related

How change a string looks like array to a real aray

I have a string, it looks like a array but not a real array. So my question is how to make it to a real array.
let string = "["abc", "cde"]";
// how to make string become an array
change string to an array
First you need to make sure your string is invalid format
"["abc", "cde"]" // invalid
"[abc, cde]" // invalid
"[11, 22]" // valid,if you do not want to use quote to wrap it,then the elements need to be number
"['abc', 'cde']" // valid
let string = `["abc", "cde"]`
const array = JSON.parse(string)
console.log(array)
You can do something like this
let data = "['abc', 'pqr', 'xxx']";
data = data.replace(/'/g, '"');
console.log(data)
const convertedArray = JSON.parse(data);
console.log(convertedArray)
Observation : Your input string is not a valid JSON string.
Solution : Double quotes besides the array items should be escaped to parse it properly. Your final string should be.
let string = "[\"abc\", \"cde\"]";
Now you can parse it using JSON.parse() method.
Live Demo :
let string = "['abc', 'cde']";
string = string.replace(/'/g, '"');
console.log(string); // "[\"abc\", \"cde\"]"
console.log(JSON.parse(string)); // ["abc", "cde"]

How to parse a string containing equal signs to object

I have a string variable
let stringValue = "{DATA={VERSION=1.1, STATE=true, STATUS=ONLINE}}"
I would like to parse it to object as result where result will be:
let result = {"DATA":{"VERSION":1.1, "STATE": true, "STATUS": "ONLINE"}}
How would you convert a stringValue to result object so it would be possible to access the nested keys?
console.log(result.DATA.STATUS)
Under the assumption that keys and string values are fully capitalized:
I used the regex /[A-Z]+/g and .match(regex) to get an array of every all caps word in the string.
Create a Set out of the the array to remove duplicates and avoid repeating the next step on the same string multiple times.
Then iterate over each word and replace it in the main string with itself between quotes. DATA => "DATA"
Then replace = with :
And finally JSON.parse() and we get the object.
let stringValue = "{DATA={VERSION=1.1, STATE=true, STATUS=ONLINE}}";
let regex = /[A-Z]+/g
let objectStrings = stringValue.match(regex)
let uniqueStrings = [... new Set(objectStrings)]
uniqueStrings.forEach((string) => stringValue = stringValue.replaceAll(string, '"'+string+'"'));
stringValue = stringValue.replaceAll('=', ':');
console.log(JSON.parse(stringValue))
Here it is in JSBin to show that the keys are properly assigned without the quotes.

Converting int array in string format to array

I have an array of integers stored in string format.
eg:
"[3,2,1]"
How can I convert this to an actual array?
I've searched high and low for a simple solution but I can't seem to find it.
Passing the string into JSON.parse and $.parseJSON results in "[" being shown for the 0 index. So I'm assuming it's not doing anything.
var arr = JSON.parse("[3,2,1]")
var text = "[3,2,1]";
var obj = JSON.parse(text);
console.log(obj);
You could use jQuery $.parseJSON() method :
var arr = $.parseJSON("[3,2,1]");
var str = "[3,2,1]";
console.log( $.parseJSON(str) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or pure javascript method JSON.parse() :
var arr = JSON.parse("[3,2,1]");
Hope this helps.
var str = "[3,2,1]";
console.log( JSON.parse("[3,2,1]") );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So I've figured out I needed to slice the first and last characters off as for some reason the string was being returned as ""[3,2,1]"" rather than "[3,2,1]" even though it's stored without quotes.
From your updated description it appears you have a string that starts and ends with ", so a simple JSON.parse will not work, since that will just convert what's between the "'s to a string. You need to either JSON.parse twice, since you have an array of integers embedded in a string, or manually parse.
JSON.parse twice way:
var str = '"[3,2,1]"';
var parsedStr = JSON.parse(str); // results in a string with contents [3,2,1]
var intArray = JSON.parse(parsedStr); // results in an int array with contents [3,2,1]
Or, if format could change to be non-JSON at some point, manual way:
var str = '"[3,2,1]"';
var intArray = [];
str.substr(2,str.length-3).split(/,/g).forEach(function(numStr) {
intArray.push(parseInt(numStr));
});

How to Convert Array-like String to Array

I have a string that looks like an array: "[918,919]". I would like to convert it to an array, is there an easier way to do this than to split and check if it is a number? Thanks
Use JSON.parse.
var myArray = JSON.parse("[918,919]");
You can get rid of the brackets at the beginning and the end, then use:
str.split(",")
which will return an array split by the comma character.
EDIT
var temp = new Array();
temp = "[918,919]".slice( 1, -1).split(",");
for (a in temp ) {
temp[a] = parseInt(temp[a]);
}
If you use JSON.parse the string must have " and not ' otherwise the code will fail.
for example:
let my_safe_string = "['foo','bar',123]";
let myArray = JSON.parse(my_safe_string)
the code will fail with
Uncaught SyntaxError: Unexpected token ' in JSON at position 1
instead if you use " all will work
let my_safe_string = "["foo","bar",123]";
let myArray = JSON.parse(my_safe_string);
so you have two possibility to cast string array like to array:
Replace ' with " my_safe_string.replace("'",'"'); and after do JSON.parse
If you are extremely sure that your string contain only string array you can use eval:
example:
let myArray = eval(my_safe_string );

Using JS Regex to obtain the first value proceeding a string with dynamic trailing values

Given the following string variations:
var string = "groups/Da12312a"
var string = "groups/Da12312a/search"
var string = "groups/Da12312a/search/sam"
var string = "groups/3131"
var string = "groups/444/search"
var string = "groups/123asdadsZad/search/sam"
How can I get back just the value following groups/ and ending at the first '/'?
desired output:
Da12312a
Da12312a
Da12312a
3131
444
123asdadsZad
Using jQuery or JavaScript? Thanks
You can use the split method.
string.split("/")[1];
I would use a simple regular expression.
var str = 'groups/foo';
var matches = /groups\/([^/]*)/.exec(str);
matches will now contain an array where index 0 is "groups/100" and index 1 is "foo".
["groups/foo", "foo"]
If you want a regex, you can use the following:
/^[^\/]*?\/([^\/]*).*/
Basically the captured group yields your desired result.
Use like:
"groups/Da12312a/search".match(/^[^\/]*?\/([^\/]*).*/)
["groups/Da12312a/search", "Da12312a"]
"groups/Da12312a".match(/^[^\/]*?\/([^\/]*).*/)
["groups/Da12312a", "Da12312a"]
"groups/3131".match(/^[^\/]*?\/([^\/]*).*/)
["groups/3131", "3131"]
As you can see, in each of the cases the array index [1] is your result.
Hope that helps.
var output = string.split('/')[1];
String.split reference.
Here's a demo with your provided examples and output.

Categories

Resources