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
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.
(
Capture group 1.*?
Match any character, as few as possible[^n\-]
Match a character other thanor
-
or a newline)
Close group 1-
Match literallyYou 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 usingt
here:Note that you need
\
in the string to make it include thes.
It first replaces the
-
, then removes any\
and finally splits. If you want to keep thein the string, just remove
.replace(/\/g, "")
.