0

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.

4
  • 3
    For what reason do you need to do this? It sounds very much like an X/Y question, where you're asking about an attempted solution instead of describing the actual problem, when there may be much better, and simpler, solutions Commented Aug 9, 2018 at 18:12
  • The first string is actually a name element for a dynamically created input. All the non numeric elements are constantly generated but the number changes on each iteration of the creation of that input. I need to know the "location number" so I can remove validation flags once the user fixes the validation problems. Commented Aug 9, 2018 at 18:15
  • So in turn that string must be coming from somewhere, so the 1 value must be retrievable/accessible from there...? Commented Aug 9, 2018 at 18:16
  • I am doing my validation on the php side and adding a class to jquery tab element if it finds that elements within that tag have an error. I can remove the individual error messages once the user meets with the validation requirements but the correct tab is harder to target. I have tried to use $(this).closest('.tab') but jQuery isn't finding it. Commented Aug 9, 2018 at 18:19

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

you don't need the g in your regex. It will make the match slower if you keep it in.
You do indeed need /g - otherwise, you get [ "franchise" ] only
0

You could try

 const str = 'franchise[location][1][location_name]';
 const res = str.split(/\W+/).map(i => { return Number(i) ? Number(i) : i;})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.