How to convert string to array of object? - javascript

I have the following string:
"[['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]"
and I want to convert it to array of object
[['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]
I've tried to do many things but I could not
function nextQuess() {
var ffa = JSON.stringify("<%- hola %>"); // from ejs variable "[['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]"
// var ff = JSON.parse([ffa])
// console.log('hello', ff);
console.log("Hello", ffa);
}

You need to replace ' by " and then parse
'(.*?)'(?=(,|\])
'(.*?)' - Match ' followed by anything zero more time ( Lazy mode ) ( Capture group 1)
(?=(,|\])) - Match must be followed by , or ]
let str = "[['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]"
let replacedString = str.replace(/'(.*?)'(?=(,|\]))/g, "\"$1\"")
let final = JSON.parse(replacedString)
console.log(final)

Use JSON.stringify(json) and then JSON.parse()
let jsonString = JSON.stringify([['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]);
let array = JSON.parse(jsonString);
console.log(array);
Or you can also try eval() method
let jsonArray = eval([['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]);
console.log(jsonArray);

Related

Convert a string of an array to an array js

Why cant i convert this arr
let stringarr = "[2022/07/12, 2022/08/09]"
to this arr
let arr = JSON.parse(stringarr) ---> error
Unexpected token / in JSON at position 5
It's not valid JSON, since the array elements aren't quoted.
If the array elements are all dates formatted like that, you could use a regular expression to extract them.
let stringarr = "[2022/07/12, 2022/08/09]"
let dates = stringarr.match(/\d{4}\/\d{2}\/\d{2}/g);
console.log(dates);
what can i do then to convert it to an array
There are several ways to do that, if the format of the string stays like this. Here's an idea.
console.log(`[2022/07/12, 2022/08/09]`
.slice(1, -1)
.split(`, `));
Or edit to create a valid JSON string:
const dateArray = JSON.parse(
`[2022/07/12, 2022/08/09]`
.replace(/\[/, `["`)
.replace(/\]/, `"]`)
.replace(/, /g, `", "`));
console.log(dateArray);
Or indeed use the match method #Barmar supplied.
const regexp = /\d+\/\d+\/\d+/g;
const stringarr = "[2022/07/12, 2022/08/09]";
const arr = [...stringarr.matchAll(regexp)];
console.log(arr)
It's to much simple 😄.
As your input is a valid array in string format. So, remove [ ] brackets and split with comma (,). Then it automatically generates an array.
let stringarr = "[2022/07/12, 2022/08/09]";
let arr = stringarr.replace(/(\[|\])/g, '').split(',');
Output:
['2022/07/12', ' 2022/08/09']

Regex matching dates in a string in Javascript

Following up from this thread, im trying to make this work
JavaScript regular expression to match X digits only
string = '2016-2022'
re = /\d{4}/g
result = [...string.matchAll(re)]
This returns an array of two arrays. Is there a way to consolidate this into 1 array?
However it doesn't look like this is returning the desired results
I'm new to regular expression. What am I doing wrong?
this return an array of matches
result = string.match(re)
This is a function to parse the string encoding those two year values and return the inner years as items of an array:
let o = parseYearsInterval('2016-2022');
console.log(o);
function parseYearsInterval(encodedValue){
var myregexp = /(\d{4})-(\d{4})/;
var match = myregexp.exec(encodedValue);
if (match != null) {
let d1 = match[1];
let d2 = match[2];
//return `[${d1}, ${d2}]`;
let result = [];
result.push(d1);
result.push(d2);
return result;
} else {
return "not valid input";
}
}
I think there are better ways to do that like splitting the string against the "-" separator and return that value as is like:
console.log ( "2016-2022".split('-') )
Just do a split if you know that only years are in the string and the strucutre isn't changing:
let arr = str.split("-");
Question
string = '2016-2022'
re = /\d{4}/g
result = [...string.matchAll(re)]
This returns an array of two arrays. Is there a way to consolidate
this into 1 array?
Solution
You may simply flat the result of matchAll.
let string = '2016-2022'
let re = /\d{4}/g
console.log([...string.matchAll(re)].flat())
Alternative
If your structure is given like "yyyy-yyyy-yyyy" you might consider a simple split
console.log('2016-2022'.split('-'))
var str = '2016-2022';
var result = [];
str.replace(/\d{4}/g, function(match, i, original) {
result.push(match);
return '';
});
console.log(result);
I also wanted to mention, that matchAll does basicly nothing else then an while exec, that's why you get 2 arrays, you can do it by yourself in a while loop and just save back what you need
var result = [];
var matches;
var regexp = /\d{4}/g;
while (matches = regexp.exec('2016-2022')) result.push(matches[0]);
console.log(result);

String cutting with Javascript

I have a string like "home/back/step" new string must be like "home/back".
In other words, I have to remove the last word with '/'. Initial string always has a different length, but the format is the same "word1/word2/word3/word4/word5...."
var x = "home/back/step";
var splitted = x.split("/");
splitted.pop();
var str = splitted.join("/");
console.log(str);
Take the string and split using ("/"), then remove the last element of array and re-join with ("/")
Use substr and remove everything after the last /
let str = "home/back/step";
let result = str.substr(0, str.lastIndexOf("/"));
console.log(result);
You could use arrays to remove the last word
const text = 'home/back/step';
const removeLastWord = s =>{
let a = s.split('/');
a.pop();
return a.join('/');
}
console.log(removeLastWord(text));
Seems I got a solution
var s = "your/string/fft";
var withoutLastChunk = s.slice(0, s.lastIndexOf("/"));
console.log(withoutLastChunk)
You can turn a string in javascript into an array of values using the split() function. (pass it the value you want to split on)
var inputString = 'home/back/step'
var arrayOfValues = inputString.split('/');
Once you have an array, you can remove the final value using pop()
arrayOfValues.pop()
You can convert an array back to a string with the join function (pass it the character to place in between your values)
return arrayOfValues.join('/')
The final function would look like:
function cutString(inputString) {
var arrayOfValues = inputString.split('/')
arrayOfValues.pop()
return arrayOfValues.join('/')
}
console.log(cutString('home/back/step'))
You can split the string on the '/', remove the last element with pop() and then join again the elements with '/'.
Something like:
str.split('/');
str.pop();
str.join('/');
Where str is the variable with your text.

From string to an Object with Javascript

How can I convert this string: "{one=1,two=2}" into an object with JavaScript? So I can access the values.
I tried replacing the "=" for ":", but then while accessing the object I receive an "undefined". Here is my code:
var numbers = "{one=1,two=2}"; //This is how I receive the string
numbers = numbers.replace(/=/g, ':'); //I use the '/g' to replace all the ocurrencies
document.write(numbers.one); //prints undefined
So this is the string
var str = '{one=1,two=2}';
replace = character to : and also make this as a valid JSON object (needs keys with double-quotes around)
var str_for_json = str.replace(/(\w+)=/g, '"$1"=').replace(/=/g, ':');
In regex, \w means [a-zA-Z0-9_] and the ( ) capture what's inside, usable later like here with $1
Now parse your string to JSON in order to use like that
var str_json = JSON.parse(str_for_json);
Now enjoy. Cheers!!
document.write(str_json.one);
FINALLY :
var str = '{one=1,two=2}';
var str_for_json = str.replace(/(\w+)=/g, '"$1"=').replace(/=/g, ':');
try {
var str_json = JSON.parse(str_for_json);
document.write(str_json.one);
} catch(e) {
console.log("Not valid JSON:" + e);
};
Instead of trying to use regexp to create JSON, I would simply parse the string directly, as in
const result = {};
numbers.match(/{(.*?)}/)[1] // get what's between curlies
.split(',') // split apart key/value pairs
.map(pair => pair.split('=')) // split pairs into key and value
.forEach(([key, value]) => // for each key and value
result[key] = value); // set it in the object
1 - a valide JSON is :var numbers = "{\"one\"=1,\"two\"=2}"; (you need the \")
2- you need to JSON.parse the strign
So this works:
var numbers = "{\"one\"=1,\"two\"=2}"; //This is how I receive the string
numbers = numbers.replace(/=/g, ':'); //I use the '/g' to replace all the ocurrencies
numbers=JSON.parse(numbers);
document.write(numbers.one); //prints undefined
But, it's bad practice !

javascript get characters between slashes

Can someone please help. I need to get the characters between two slashes e.g:
Car/Saloon/827365/1728374
I need to get the characters between the second and third slashes. i.e 827365
You can use the split() method of the String prototype, passing in the slash as the separator string:
const value = 'Car/Saloon/827365/1728374';
const parts = value.split('/');
// parts is now a string array, containing:
// [ "Car", "Saloon", "827365", "1728374" ]
// So you can get the requested part like this:
const interestingPart = parts[2];
It's also possible to achieve this as a one-liner:
const interestingPart = value.split('/')[2];
Documentation is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
This will simply alert 1728374, as you want
alert("Car/Saloon/827365/1728374".split('/')[3]);
or, a bit longer, but also more readable:
var str = "Car/Saloon/827365/1728374";
var exploded = str.split('/');
/**
* str[0] is Car
* str[1] is Saloon
* str[2] is 827365
* str[3] is 1728374
*/
Try the_string.split('/') - it gives you an array containing the substrings between the slashes.
try this:
var str = 'Car/Saloon/827365/1728374';
var arr = str.split('/'); // returns array, iterate through it to get the required element
Use split to divide the string in four parts:
'Car/Saloon/827365/1728374'.split('/')[2]
Gives "827365"
You will have to use the .split() function like this:
("Car/Saloon/827365/1728374").split("/")[2];
"Car/Saloon/827365/1728374".split("/")[2]
"Car/Saloon/827365/1728374".split("/")[3]
How many you want you take it.. :)
var str = "Car/Saloon/827365/1728374";
var items = str.split("/");
for (var i = 0; i < items.length; i++)
{
alert(items[i]);
}
OR
var lastItem = items[items.length - 1]; // yeilds 1728374
OR
var lastItem1728374 = items[2];

Categories