Home > database >  Can someone help me with this javascript regex to turn a string of list items into an array with the
Can someone help me with this javascript regex to turn a string of list items into an array with the

Time:05-22

I have 2 kinds of strings coming back from an API. They look as follows:

let string1 = "\n1. foo\n2. bar\n3. foobar"
let string2 = "\n\n1. foo.\n\n2. bar.\n\n3. foobar."

To be clear, string 1 will always have 3 items coming back, string 2 has an unknown number of items coming back. But very similar patterns.

What I want to do is pull out the text only from each item into an array.

So from string1 I want ["foo", "bar", "foobar"] From string2 I want ["foo.", "bar.", "foobar."]

I'm awful at regex but I somehow stumbled myself into an expression that accomplishes this for both string types, however, it uses regex's lookbehind which I'm trying to avoid as it isn't supported in all browsers:

let regex = /(?<=\. )(.*[a-zA-Z])/g;
let resultArray = str.match(regex);

Would someone be able to help me refactor this regex into something that doesn't use lookbehind?

CodePudding user response:

OP's code, which uses a String.match, is actually better than the proposed solutions. It only needed a minor tweak to make it work, which is what the question asked:

string1.match(/([A-z]. )/g)

// TEST

[

 "\n1. foo\n2. bar\n3. foobar", 
 "\n\n1. foo.\n\n2. bar.\n\n3. foobar."

].forEach(p => {

  console.log( p.match(/([A-z]. )/g) )

});

CodePudding user response:

EDIT: see @Oleg-Barabanov 's solution, it's technically a bit quicker.

string.replace(/\n[0-9.]*/g, "").split(" ").slice(1)
  • \n for the new line
  • 0-9 for digits (also could use \d
  • . for the dot after the number
  • g to replace all
  • .split(" ") to chop it up wherever there's a space (\s)

Demo:

let string1 = "\n1. foo\n2. bar\n3. foobar"
let string2 = "\n\n1. foo.\n\n2. bar.\n\n3. foobar."

const parse = (str) => str.replace(/\n[0-9.]*/g, "").split(" ").slice(1)


console.log(parse(string1))
console.log(parse(string2))

CodePudding user response:

If I understood you correctly, then perhaps this solution can help you:

const string1 = "\n1. foo\n2. bar\n3. foobar";
const string2 = "\n\n1. foo.\n\n2. bar.\n\n3. foobar.";

const parse = (str) => {
  return str.split(/\n[0-9.\s]*/g).filter((item) => item !== "");
}

console.log('Example 1:', parse(string1));
console.log('Example 2:', parse(string2));

  • Related