How to parse a string containing equal signs to object - javascript

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.

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"]

Extract part of a string which start with a certain word in Javascript

I have the following string
"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,
I need to get string after "ssu":" the Result should be 89c4eef0-3a0d-47ae-a97f-42adafa7cf8f. How do I do it in Javascript but very simple? I am thinking to collect 36 character after "ssu":".
You could build a valid JSON string and parse it and get the wanted property ssu.
var string = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,',
object = JSON.parse(`{${string.slice(0, -1)}}`), // slice for removing the last comma
ssu = object.ssu;
console.log(ssu);
One solution would be to use the following regular expression:
/\"ssu\":\"([\w-]+)\"/
This pattern basically means:
\"ssu\":\" , start searching from the first instance of "ssu":"
([\w-]+) , collect a "group" of one or more alphanumeric characters \w and hypens -
\", look for a " at the end of the group
Using a group allows you to extract a portion of the matched pattern via the String#match method that is of interest to you which in your case is the guid that corresponds to ([\w-]+)
A working example of this would be:
const str = `"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,`
const value = str.match(/\"ssu\":\"([\w-]+)\"/)[1]
console.log(value);
Update: Extract multiple groupings that occour in string
To extract values for multiple occurances of the "ssu" key in your input string, you could use the String#matchAll() method to achieve that as shown:
const str = `"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,"ssu":"value-of-second-ssu","ssu":"value-of-third-ssu"`;
const values =
/* Obtain array of matches for pattern */
[...str.matchAll(/\"ssu\":\"([\w-]+)\"/g)]
/* Extract only the value from pattern group */
.map(([,value]) => value);
console.log(values);
Note that for this to work as expected, the /g flag must be added to the end of the original pattern. Hope that helps!
Use this regExp: /(?!"ssu":")(\w+-)+\w+/
const str = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,';
const re = /(?!"ssu":")(\w+-)+\w+/;
const res = str.match(re)[0];
console.log(res);
You can use regular expressions.
var str = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,'
var minhaRE = new RegExp("[a-z|0-9]*-[a-z|0-9|-]*");
minhaRE.exec(str)
OutPut: Array [ "89c4eef0-3a0d-47ae-a97f-42adafa7cf8f" ]
Looks almost like a JSON string.
So with a small change it can be parsed to an object.
var str = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049, ';
var obj = JSON.parse('{'+str.replace(/[, ]+$/,'')+'}');
console.log(obj.ssu)

Alternative eval() to execute the string

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)

Why [,,].join(' ') length is one less than array length?

What is the reason behind the length of string produced by joining var arr = [,,], like so: var str = arr.join(' ') being one less than length of arr.
var literal_arr = [,,],
joined_literal_arr = literal_arr.join(' '),
constructor_arr = new Array(2),
joined_constructor_arr = new Array(2).join(' ');
console.log("Literal array notation length = ", literal_arr.length);
console.log("Joined literal array notation string length = ", joined_literal_arr.length);
console.log("Constructor array notation length = ", constructor_arr.length);
console.log("Joined constructor notation string length = ", joined_constructor_arr.length);
As per MDN docs :
If an element is undefined or null, it is converted to the empty string.
In your case, you are creating an array with a particular length without any value(it would be undefined). So while joining there will be length - 1 separators(since undefined already treated as an empty string) means length - 1 spaces(' ').
It is simple as .join will join array elements with separator provided as argument. It won’t append separator after the last element or prepend it before the first element. It will place separator between elements only.

Extract strings between occurences of a specific character

I'm attempting to extract strings between occurences of a specific character in a larger string.
For example:
The initial string is:
var str = "http://www.google.com?hello?kitty?test";
I want to be able to store all of the substrings between the question marks as their own variables, such as "hello", "kitty" and "test".
How would I target substrings between different indexes of a specific character using either JavaScript or Regular Expressions?
You could split on ? and use slice passing 1 as the parameter value.
That would give you an array with your values. If you want to create separate variables you could for example get the value by its index var1 = parts[0]
var str = "http://www.google.com?hello?kitty?test";
var parts = str.split('?').slice(1);
console.log(parts);
var var1 = parts[0],
var2 = parts[1],
var3 = parts[2];
console.log(var1);
console.log(var2);
console.log(var3);
Quick note: that URL would be invalid. A question mark ? denotes the beginning of a query string and key/value pairs are generally provided in the form key=value and delimited with an ampersand &.
That being said, if this isn't a problem then why not split on the question mark to obtain an array of values?
var split_values = str.split('?');
//result: [ 'http://www.google.com', 'hello', 'kitty', 'test' ]
Then you could simply grab the individual values from the array, skipping the first element.
I believe this will do it:
var components = "http://www.google.com?hello?kitty?test".split("?");
components.slice(1-components.length) // Returns: [ "hello", "kitty", "test" ]
using Regular Expressions
var reg = /\?([^\?]+)/g;
var s = "http://www.google.com?hello?kitty?test";
var results = null;
while( results = reg.exec(s) ){
console.log(results[1]);
}
The general case is to use RegExp:
var regex1 = new RegExp(/\?.*?(?=\?|$)/,'g'); regex1.lastIndex=0;
str.match(regex1)
Note that this will also get you the leading ? in each clause (no look-behind regexp in Javascript).
Alternatively you can use the sticky flag and run it in a loop:
var regex1 = new RegExp(/.*?\?(.*?)(?=\?|$)/,'y'); regex1.lastIndex=0;
while(str.match(regex1)) {...}
You can take the substring starting from the first question mark, then split by question mark
const str = "http://www.google.com?hello?kitty?test";
const matches = str.substring(str.indexOf('?') + 1).split(/\?/g);
console.log(matches);

Categories

Resources