skip to Main Content

This code doesn’t work in safari 15, so need another way to solve it without lookbehind

const re = /(?<!\)(?<!-)-/g;
const str = '20-30--40\---50--60';
console.log(str.split(re));

output:

['20', '30', '-40\---50', '-60']

What this code does:
Need to split the string into parts.
For example.

"10-20" -> ['10', '20']

but need to split only the first ‘-‘ and keep all ‘-‘ before the value, i.e.

"10---20" -> ['10', '--20']

and finally, it should be possible to escape with :

"10---20--30"  -> ['10', '--20', '-30']
"10---20--30" -> ['10', '--20--30']

I don’t know much about regex, chatgpt and alternatives couldn’t help me.

2

Answers


  1. You don’t need a lookbehind assertion, you can use a capture group instead to keep the values that you are splitting on.

    After splitting remove the empty entries.

    (.*?[^n\-])-
    
    • ( Capture group 1
      • .*? Match any character, as few as possible
      • [^n\-] Match a character other than or - or a newline
    • ) Close group 1
    • - Match literally
    const regex = /(.*?[^n\-])-/;
    const strings = [
      "20-30--40\---50--60",
      "10-20",
      "10---20",
      "10---20--30",
      "10---20\--30"
    ]
    
    strings.forEach(s =>
      console.log(
        s.split(regex)
        .filter(Boolean)
      )
    )
    Login or Signup to reply.
  2. You could do it in two steps: First replace the - where you want to split with a character that doesn’t exist in the string and then split on that character. I’m using t here:

    var strings = ["10-20", "10---20", "10---20--30", "10---20\--30"];
    
    for(str of strings) {
      console.log(str);
      console.log(str.replace(/(d)-/g, "$1t").replace(/\/g, "").split(/t/));
    }

    Note that you need \ in the string to make it include the s.
    It first replaces the -, then removes any \ and finally splits. If you want to keep the in the string, just remove .replace(/\/g, "").

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search