0

How i can split string in js for result:

result = ["post_address", "location", "area"]

This is problem? Need help with re

let re = ???
let arr = "post_address[location][area]".split(re)
2
  • Please show an input example and expected output. You may want to look at destructuring Commented Nov 16, 2017 at 9:26
  • @mplungjan I agree. It is not clear what we are trying. I want to see the desired i/o. Commented Nov 16, 2017 at 9:30

4 Answers 4

2

Simply split by /\[|\]/ and the remove the empty strings.

var output = "post_address[location][area]".split(/\[|\]/).filter((s)=>s.length > 0);

console.log(output);

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

Comments

0

You can use regexp like this :

var re = /^(\w*)\[(\w*)\]\[(\w*)\]$/gi;

Comments

0

Use Lodash:

const str = "post_address[location][area]";
const output = _.compact(_.split(str, /\[|\]/));
console.log(output);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Comments

0

There is the shorter way

enter image description here

It is actually the same as

'post_address[location][area]'.split(/[^\w]+/).filter(i => i)

console.log(
    'post_address[location][area]'.match(/(\w+)/g)
);

console.log(
    'post_address[location][area]'.split(/[^\w]+/).filter(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.