Marko
Marko

Reputation: 390

I have a positive lookbehind Safari error

Hi guys I have a small issue with Regex that doesn't work in safari.

This is the problem:

Title = "Level 5 All programmes"

I am trying to separate it with positive lookbehind to keep the number in the first item of array like this:

Title.split(/(?<=[0-9])/)

And I get this

["Level 5", " all specialisation"]

Which is good, but the problem is that this solution doesn't work in Safari.

Do you guys have any idea how to solve this?

Upvotes: 1

Views: 724

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626926

You may match and capture the parts with /(.*?\d+)(\s.*)/ regex:

var Title = "Level 5 All programmes";
var rx = /(.*?\d+)(\s.*)/;
var m = Title.match(rx);
if (m) {
  console.log("First part: '" + m[1] + "'\nSecond part: '"+ m[2] + "'");
}

The /(.*?\d+)(\s.*)/ regex matches

  • (.*?\d+) - Group 1: any zero or more chars other than line break chars as few as possible and then 1+ digits
  • (\s.*) - Group 2: a whitespace char followed with any zero or more chars other than line break chars as many as possible.

To match across lines, replace . with [^] or [\s\S].

For the cases when there is no second part, make the second group optional and when getting a match, check if Group 2 value is not undefined:

var Title = "Level 5";
var rx = /(.*?\d+)(\s.*)?/;
var m = Title.match(rx);
if (m) {
  console.log("First part: '" + m[1] + "'");
  if (m[2] !== undefined) console.log("Second part: '"+ m[2] + "'");
}

Upvotes: 1

Related Questions