0

I have a string:

"Community - Moderate Environment - Minor Financial - Major Health & Safety - Extreme "

I want to split this string into:

Community - Moderate

Environment - Minor

Financial - Major

Health & Safety - Extreme

its like give newline after one category,

how do I get that

I try to split:

var t = Community - Moderate Environment - Minor Financial - Major Health & Safety - Extreme

t.split('-')

after that I don't know what can I do

4
  • split creates an array. Do you actually want an array, or just a new string with newlines? Commented Dec 6, 2018 at 8:10
  • string with new line Commented Dec 6, 2018 at 8:12
  • this is not a question following the stackoverflow guidelines. it does not show an attempt of solving this yourself. Commented Dec 6, 2018 at 8:13
  • That's kind of impossible. What should Word1 - Word2 Word3 Word4 - Word5 split into? It can either be Word1 - Word2 Word3 and Word4 - Word5 or Word1 - Word2 and Word3 Word4 - Word5 Commented Dec 6, 2018 at 8:14

1 Answer 1

1

Use .replace instead of split to replace the word after a - with that word concatenated with a newline:

const str = "Community - Moderate Environment - Minor Financial - Major Health & Safety - Extreme ";
console.log(str.trim().replace(/(- \w+) +/g, '$1\n'));

The regular expression

/(- \w+) +/

captures a dash, followed by a space, followed by word characters, in a group. Then, it matches spaces, so that the whole match can be replaced with the first capture group - effectively replacing the spaces with newline characters.

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

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.