javascript split string like object/array to nodes - javascript

I have a string like object/array nodes. need to convert string to nodes, using regular expression
const variableName = "parent1[0].child[2].grandChild['name'].deep_child"; // should be n number of child`
// expected result:
const array = ['parent1',0,'child',2,'grandChild','name','deepChild'];
// Note: array's strings property should be any valid variable name like 'parenet' or 'parent1' or 'PARENT' or '_parent_' or 'deep_child'
Note

You can get the desired result by using split
[^\w]
after splitting you may get empty strings so you can use a filter to filter out them. At last convert the required number that are in string to type number
const variableName = "parent1[0].child[2].grandChild['name'].deep_child";
const result = variableName
.split(/[^\w]/)
.filter(_ => _)
.map(a => (isNaN(parseInt(a)) ? a : parseInt(a)));
console.log(result);

Try with regex /[\[\].']+/g.
Regex Evaluator.
This regex catches the group between [ and ]. and splits the string there. Also if ant node of the generated array is a number, convert that to a number using a map function.
const variableName = "parent1[0].child[2].grandChild['name'].deep_child";
const output = variableName
.split(/[\[\].']+/g)
.map((node) => isNaN(node) ? node : Number(node));
console.log(output);

What you are looking for is a split of multiple conditions. A simple and good aproach is to replace all of them except one and finally make the split:
// should be n number of child`
const variableName = "parent1[0].child[2].grandChild['name'].deep_child";
const array = variableName
.replaceAll("'", "")
.replaceAll("].", "[")
.split("[")
.map((x) => (isNaN(x) ? x : +x));
console.log(array);

Related

how to print all values from an array containing a given string value (JavaScript)

Given an array like the below code :
let words = ['bring','constant','bath','spring','splashing']
How do I print all string characters with ing characters from the words array ?
You need to use endsWith method to check if the word ends with a specific value.
let words = ['bring','constant','bath','spring','splashing']
const result = words.filter(w => w.endsWith('ing'))
result.forEach(w => console.log(w))
You also can use regular expressions with dollar sign $ means end with.
let words = ['bring','constant','bath','spring','splashing']
const result = words.filter(w => /(ing)$/.test(w))
result.forEach(w => console.log(w))
As author want to check if ing exist in the middle of the word or not. In that case you can just use normal regex with String.match() method without $ sign at end.
Live Demo :
let words = ['bring','constant','bath','spring','splashing', 'tingtong'];
const res = words.filter(word => word.match(/ing/ig));
console.log(res);
Or you can also achieve that by using .includes() method.
Live Demo :
let words = ['bring','constant','bath','spring','splashing', 'tingtong'];
const res = words.filter(word => word.includes('ing'));
console.log(res);

How to take value using regular expressions?

I have such a string "Categ=All&Search=Jucs&Kin=LUU".How to get an array of values from this line [All,Jucs,LUU].
Here is an example
let x = /(\b\w+)$|(\b\w+)\b&/g;
let y = "Categories=All&Search=Filus";
console.log(y.match(x));
but I wanted no character &.
Since this looks like a URL query string, you can treat it as one and parse the data without needing a regex.
let query = "Categ=All&Search=Jucs&Kin=LUU",
parser = new URLSearchParams(query),
values = [];
parser.forEach(function(v, k){
values.push(v);
});
console.log(values);
Docs: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
Note: This may not work in IE, if that's something you care about.
Loop through all matches and take only the first group, ignoring the =
let x = /=([^&]+)/g;
let y = "Categories=All&Search=Filus";
let match;
while (match = x.exec(y)) {
console.log(match[1]);
}
To achieve expected result, use below option of using split and filter with index to separate Keys and values
1. Use split([^A-Za-z0-9]) to split string based on any special character other letters and numbers
2. Use Filter and index to get even or odd elements of array for keys and values
var str1 = "Categ=All&Search=Jucs&Kin=LUU";
function splitter(str, index){
return str.split(/[^A-Za-z0-9]/).filter((v,i)=>i%2=== index);
}
console.log(splitter(str1, 0)) //["Categ", "Search", "Kin"]
console.log(splitter(str1, 1))//["All", "Jucs", "LUU"]
codepen - https://codepen.io/nagasai/pen/yWMYwz?editors=1010

Split a declartion of an array string into an array of strings

What would be the best way to split an a string that a declaration of an array into an array of strings using javascript/jquery. An example of a string I am working with:
franchise[location][1][location_name]
I would like it to be converted into an array like:
['franchise', 'location', '1', 'location_name']
BONUS: If I could also get that numeric value to be an integer and not just a string in one fell swoop, that would be terrific.
You can use String.split with a regex that matches all the none alpha numeric chars.
Something like that:
const str = 'franchise[location][1][location_name]';
const result = str.split(/\W+/).filter(Boolean);
console.log(result);
One option would be to just match word characters:
console.log(
'franchise[location][1][location_name]'.match(/\w+/g)
);
To transform the "1" to a number, you might .map afterwards:
const initArr = 'franchise[location][1][location_name]'.match(/\w+/g);
console.log(initArr.map(item => !isNaN(item) ? Number(item) : item));
You could try
const str = 'franchise[location][1][location_name]';
const res = str.split(/\W+/).map(i => { return Number(i) ? Number(i) : i;})

Splitting string but leave inner strings intact?

I have a string that looks like this 'a,b,"c,d",e,"f,g,h"'.
I would like to be able to split this string on , but leave encapsulated strings intact getting the following output : ["a","b","c,d","e","f,g,h"].
Is there a way to do this without having to parse the string char by char ?
You can create a match of the strings, then map the matches and replace any " in the elements:
let f = 'a,b"c,d",e,"f,g,h"';
let matches = f.match(/\w+|(["]).*?\1/g);
let res = matches.map(e => e.replace(/"/g, ''));
console.log(res);

Convert a string of array into array javascript

In my code i am reading a hidden input value which is actually a javascript array object
<input type="hidden" id="id_num" value="{{array_values}}">
But when i taking it using jquery ($('#id_num").val()) its a string of array,
"['item1','item2','item3']"
so i can not iterate it.How should i convert into javascript array object, so that i can iterate through items in the array?
You can use JSON.parse but first you need to replace all ' with " as ' are invalid delimitters in JSON strings.
var str = "['item1','item2','item3']";
str = str.replace(/'/g, '"');
var arr = JSON.parse(str);
console.log(arr);
Another approach:
Using slice and split like this:
var str = "['item1','item2','item3']";
var arr = str.slice(1, -1) // remove [ and ]
.split(',') // this could cause trouble if the strings contain commas
.map(s => s.slice(1, -1)); // remove ' and '
console.log(arr);
You can use eval command to get values from string;
eval("[0,1,2]")
will return;
[0,1,2]
more details here
Though it should be noted, if this string value comes from users, they might inject code that would cause an issue for your structure, if this string value comes only from your logic, than it is alright to utilize eval
var arr = "['item1','item2','item3']";
var res = arr.replace(/'/g, '"')
console.log(JSON.parse(res));
A possible way of solving this:
First, substr it to remove the [..]s.
Next, remove internal quotes, since we would be getting extra when we string.split
Finally, split with ,.
let mystring = "['item1','item2','item3']";
let arr = mystring.substr(1, mystring.length - 2)
.replace(/'/g, "")
.split(",")
console.log(arr)

Categories