Get the array in a string [javascript] - javascript

I need to get the array in the string below:
"['Comedian', 'Actor']"
For example, for the above, I should get ['Comedian', 'Actor'].
Already working using eval(). Is there any other way to get the desired result?

Normally i would suggest using a JSON.parse functionality to do so, however since this is not a valid json format due to single quotes instead of double quotes you could try to first replace those and only then parse
const str = "['Comedian','Actor']";
console.log(JSON.parse(str.replace(/'/g, '"')));
or you could use JSON5
const str = "['Comedian','Actor']";
console.log(JSON5.parse(str));
<script src="https://unpkg.com/json5#^2.0.0/dist/index.min.js"></script>

Related

How to convert string to object in javascript?

const str="{a:{url:'http://localhost:80',c:1,},d:'d',e:true}"
How to get the result without using evil and new Function:
const obj={a:{url:'http://localhost:80',c:1,},d:'d',e:true}
First of all:
You need to format your string into a valid JSON format ( double quotes instead of single quotes )
And then you'll just need to JSON.parse(str)
To convert a string to json you can use JSON.parse(str)
But first make sure the string syntax is correct, there are several websites to do this, one of many is this https://jsonlint.com/

parse a string that contains array with strings

I am struggling to parse a string that contains array. And the array also contains list of arrays.
Each of the array contains string.
code here
let a = "[[48934, 'Danial Brendon', 'developer'],[48934, 'Nicki Lopez', 'developer']]";
console.log(JSON.parse(a))
I tried using JSON.parse() but did not work, may be because JSON.parse() also want to parse the string.
I am having difficulty with this even this looks simple. I could not find any similar question/answer like this.
Thanks.
To JSON parse , you need double quotes instead of single. like this ...
let a = '[[48934, "Danial Brendon", "developer"],[48934, "Nicki Lopez", "developer"]]';
console.log(JSON.parse(a));

How to handle JSON string errors (error character ") in javascript

An administrator has directly filled content into the database and formatted it as json string. However, when retrieving it from the database and parse it into json, it failed. Because when filling data directly, instead of content need to write this (\"), they just write (") the json string shield is faulty and cannot parse. How to solve this problem.
Ex:
"aaaa"dddd"aaaa" => "aaaa\"dddd\"aaaa"
I assume that when you retrieve the string from the database, you are getting something like: '"aaaa"dddd"aaaa"'
If so, then you can convert that to a valid JSON string by removing the first and last double quotes and using JSON.stringify to convert the string to a valid JSON string (including escaping the inner double quotes).
For example:
const s = '"aaaa"dddd"aaaa"';
const escaped = JSON.stringify(s.slice(1, -1));
console.log(escaped);
// "aaaa\"dddd\"aaaa"
const parsed = JSON.parse(escaped);
console.log(parsed);
// aaaa"dddd"aaaa
You might use replace with RegExp and g flag
let str = `"aaaa"dddd"aaaa"`;
let result = str.replace(/"/g,`\\"`).slice(1,-2) + '"';
console.log(result)
OP asked My database return result string "aaaa"dddd"aaaa", How to assign such "aaaa"dddd"aaaa"
You can interpolate that return from database into Template Strings
let str = `${database.value}`;
Not sure what database or what language is on server side, however, rather that trying to escape the inner quotes. Trying just replacing the first and last double quote with with a single quote. Not sure of the full context here to know whether this is the issue. Anyway, something to consider

Convert String of certain format to JSON in javascript

I have a string of the format
var str = "{key1=value1, Key2=value2}"
I need to convert this into a json object to be able to iterate through it.
Any suggestions on how this can be done? there can be any number of keys
You need first to "JSONize" this string you are getting so it can be converted to a JavaScript object using the JSON class. My guess, if the string has always this format ({key=value, ...}), is that you could parse it first like this:
var parsedString = yourString.replace(/(\b\S+\b)=(\b\S+\b)/g, '"$1":"$2"')
This way, from this: "{key1=value1, Key2=value2}" you get this: '{"key1":"value1", "Key2":"value2"}'.
Then, as someone suggested, just use JSON.parse(parsedString) to get your JS object.

Get part of string?

I have a string formatted like this:
item_questions_attributes_abc123_id
I'm specifically trying to get the abc123 bit. That string can be any alphanumeric of any case. No special characters or spaces.
I'm using jQuery, though I'm certainly fine with using straight javascript if that's the best solution.
If it's always the 4th part of the string you can use split.
var original = 'item_questions_attributes_abc123_id';
var result = original.split('_')[3];
Try this:
var myArray = myString.split("_");
alert(myArray[3]);
use split method of javascript and then use 2nd last index you will have your required data.

Categories

Resources