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

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;})

Related

Understanding how to count the characters in a string in order to use slice() on a part of the string

I am learning JavaScript , the fundamentals for now and what I don’t get, is how to count the characters in the string in order to use the slice on the certain string and extract a certain word out of the string.
For example
let text = "JavaScript", "apples", "avocado");
let newText = text.slice(?),(?);
How do I know or count the position of apples for example or JavaScript?
Thank you!
Try like this:
let text = "JavaScript, apples, avocado";
let newText = text.slice(text.indexOf("JavaScript"));
let newText2 = text.slice(text.indexOf("apples"));
console.log(newText)
console.log(newText2)
Few observations/suggestions :
String will always wrapped with the quotes but in your post it is not looks like a string.
Why you want to slice to get the word from that string ? You can convert that string into an array and then get that word.
Implementation steps :
Split string and convert that in an array using String.split() method.
Now we can find for the word you want to search from an array using Array.find() method.
Working Demo :
// Input string
const text = "JavaScript, apples, avocado";
const searchText = 'apples';
// Split string and convert that in an array using String.split() method.
const splittedStringArray = text.split(',');
// Now we can find for the word from splittedStringArray using Array.find() method.
const result = splittedStringArray.find(item => item.trim() === searchText);
// Output
console.log(result);
split the string into an array, , and then splice in the string you do want. Finally, join the array elements into a new string.
const str = 'JavaScript, apples, avocado';
function replace(str, search, replacement) {
// Create an array using `split`
const arr = str.split(', ');
// Find the index of the item you're looking for
const index = arr.findIndex(el => el === search);
// `splice` in the new replacement string
arr.splice(index, 1, replacement);
// Return the new string
return arr.join(', ');
}
console.log(replace(str, 'apples', 'biscuit'));

How create regexp for reapeted pattern?

In string available only 3 parameters :
C1 - number is only 0 or 1
R1 - number is only 0 or 1
A
String Example
"C1-R1-C0-C0-A-R0-R1-R1-A-C1"
Smth like this /[CRA]\d-/gi only for each with separetor
OR better use split and map methods?
If you are looking for a regular expression, something like this should work:
/^([CR][01]|A)(-([CR][01]|A))*$/
Essentially, we match a valid "parameter" as well as any number of "-parameter" after it. In context:
const string1 = 'C1-R1-C0-C0-A-R0-R1-R1-A-C1';
const string2 = 'invalid';
const testString = (string) => {
return /^([CR][01]|A)(-([CR][01]|A))*$/.test(string);
};
console.log(testString(string1));
console.log(testString(string2));
Output:
true
false
Use split and then filter with the regexp.
let string = "C1-R1-C0-C0-A-R0-R1-R1-A-C1";
let result = string.split('-').filter(el => /^([CR][01]|A)$/.test(el));
console.log(result);

javascript split string like object/array to nodes

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);

How can I capture word by Regex

I would like to capture the array key from a string.
Here are my words: message[0][generic][0][elements][0][default_action][url]...
I want to capture the array keys after message[0][generic][0][elements][0], and the expected results are default_action and url etc.
I have tried following patterns but not work.
message\[0\]\[generic\]\[0\]\[elements\]\[0\](?=\[(\w+)\]): it captures default_action only;
\[(\w+)\]: it captures all array keys, but includes 0, generic, elements...
Is there any regex pattern for JavaScript that make the result array inverse, like [url, default_action]?
You can replace unwanted part of a string,and then get all other keys.
var string = 'message[0][generic][0][elements][0][default_action][url][imthird]';
var regexp = /message\[0\]\[generic\]\[0\]\[elements\]\[0\]/
var answer = string.replace(regexp,'').match(/[^\[\]]+/g)
console.log(answer);
To extract any number of keys and reverse the order of the elements in resulting array:
str = "message[0][generic][0][elements][0][default_action][url]";
res = str.match(/\[([^\d\]]+)\](?=\[[^\d\]]*\]|$)/g)
.map(function(s) { return s.replace(/[\[\]]/g, "") })
.reverse();
console.log(res);
The solution using String.prototype.split() and Array.prototype.slice() functions:
var s = 'message[0][generic][0][elements][0][default_action][url]...',
result = s.split(/\]\[|[\[\]]/g).slice(-3,-1);
console.log(result);

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);

Categories