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. Feb 16, 2018 at 4:16
  • Are you trying to match \d) too? Such as 1) Option x ?
    – frogcoder
    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"
]
*/

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.