0

I would like to split a string base on regex.

Expected input:

1. recipe description. 2. second step of the description that takes 30 minutes. 3. third step of the description that contain 20g of flour.

Now like to split the string based on the starting number. Is that possible?

Expected outcome:

[
"recipe description.",
"second step of the description that takes 30 minutes.",
"third step of the description that contain 20g of flour."
]

I already tried it with const steps = text.split(new RegExp("/^d./", "g")); but its not the expected outcome i would like to have.

2
  • code is looking fro start of a string, letter d, and . is any character regexper.com/#%2F%5Ed.%2Fg and your code will have problems when you reach 10 steps once you fix the problems. Commented Feb 18, 2020 at 16:43
  • There's no need to use new RegExp() here. You're also not escaping the . character, nor are you escaping a \ character for your \d input. Just use /\d\./g directly. Also, think about using sites like regex101 or regexr to actually know what you're writing. Commented Feb 18, 2020 at 16:44

1 Answer 1

3

Try the following:

var text = "1. recipe description. 2. second step of the description that takes 30 minutes. 3. third step of the description that contain 20g of flour.";
var steps = text.split(/\s*\d+\.\s*/g).slice(1);
console.log(steps)

This splits on a number followed by full stop, possibly with whitespace on either end. Your current pattern seems to attempt to target a single digit only appearing at the start of the string, and there are other problems as well.

Slight edit: Call slice(1) on the array returned from the split, to remove a dummy empty string element resulting from the split on the first number.

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

1 Comment

The output of this has the first index being ""

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.