1

I am trying to split a string in JAVASCRIPT using regEx,

String to split = "Base text \n 1. option one \n 2. Option two \n 3. Option three \n 4. Option four"

Expected output = [Base text , option one , Option two , Option three , Option four]

But with the regEx I tries I am getting the reg ex in the array as below

[Base text ,1., option one ,2., Option two ,3., Option three ,4., Option four]

RegEx tried - String.split( new RegExp(/\s*(\d\.|\d\))/g))

String.split( new RegExp("\\s*(\\d\\.|\\d\\))\\s*"))
2
  • its better next time to just give us a complete working code segment instead of split up like this. Commented Feb 16, 2018 at 4:16
  • Are you trying to match \d) too? Such as 1) Option x ? Commented Feb 16, 2018 at 4:28

2 Answers 2

1

var str = "Base text \n 1. option one  \n 2. Option two \n 3. Option three \n 4. Option four"

var split = str.split (/\s*\n \d\.*\s*/)
console.log (split)

/* OUTPUT:
[
  "Base text",
  "option one",
  "Option two",
  "Option three",
  "Option four"
]
*/

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

Comments

0

Use this RegEx /\n \d*\. /. See the code below which uses this RegEx inside the split function.

var str = "Base text \n 1. option one  \n 2. Option two \n 3. Option three \n 4. Option four";

var regex = /\n \d*\. /;

var split_str = str.split(regex);

console.log(split_str);

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.