Gangz
Gangz

Reputation: 13

Javascript : Split string with RegEx and remove pattern from the array

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*"))

Upvotes: 1

Views: 1327

Answers (2)

Ari Singh
Ari Singh

Reputation: 1296

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"
]
*/

Upvotes: 1

Vivek
Vivek

Reputation: 2755

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

Upvotes: 0

Related Questions