Home > OS >  alternate for JS Regex lookbehind/lookahead for Safari
alternate for JS Regex lookbehind/lookahead for Safari

Time:12-01

I have a regex in JS

const messageArray = message.split(/(?<!\r)\n/gm)

Below is my 'message'.

'Hello, please can you send &#163;100.00 to  MNBVCXZLSTERIA1 on  04/08/21  \n\nhttps://www.co-operativebank.co.uk/help-and-support/faqs/accounts/savings/isas/ \r\nwhat-happens-if-i-put-too-much-money-in-my-cash-isa/PROD-2740 \n\nThank you'

As you can see above, I am receiving \r\n values inside links which is new line char and due to that it is not able to recognize link and showing in multiline.

But the above regex converts this to link in chrome correctly but not working in safari because of lookbehind/lookahead.

Spent some time trying to think about a good workaround, but did not find one. Any insight?

Thanks!

CodePudding user response:

Assuming you have \r\n only within links, and \n just outside of links you can first restore the links by removing the \r\n, then split by \n:

const input = 'Hello, please can you send &#163;100.00 to  MNBVCXZLSTERIA1 on  04/08/21  \n\nhttps://www.co-operativebank.co.uk/help-and-support/faqs/accounts/savings/isas/ \r\nwhat-happens-if-i-put-too-much-money-in-my-cash-isa/PROD-2740 \n\nThank you';
let result = input.replace(/ *\r\n/g, '').split(/\n/);
console.log(result);

Output:

[
  "Hello, please can you send &#163;100.00 to  MNBVCXZLSTERIA1 on  04/08/21  ",
  "https://www.co-operativebank.co.uk/help-and-support/faqs/accounts/savings/isas/what-happens-if-i-put-too-much-money-in-my-cash-isa/PROD-2740 ",
  "Thank you"
]

Note: To remove empty array items you can us this instead: .split(/\n /)

CodePudding user response:

You could use match instead of split, and then match multiline text when it is delimited with \r\n?.

Here a snippet with both the original method and the proposed one:

const message = 'Hello, please can you send &#163;100.00 to  MNBVCXZLSTERIA1 on  04/08/21  \n\nhttps://www.co-operativebank.co.uk/help-and-support/faqs/accounts/savings/isas/ \r\nwhat-happens-if-i-put-too-much-money-in-my-cash-isa/PROD-2740 \n\nThank you';
// With look-behind
const messageArray = message.split(/(?<!\r)\n/gm);
console.log(messageArray);
// Without lookbehind
const messageArray2 = message.match(/^.*$(\r\n?.*$)*/gm);
console.log(messageArray2);

The output is the same.

  • Related