I am trying to match each \t
in the leading whitespace of a line so I can replace them with two spaces. This is trivial with an unbounded (i.e., variable-length) lookbehind.
text.replace(/(?<=^\s*)\t/gm, ' ')
Unfortunately, this code is running on iOS, and for some reason, Safari and iOS have yet to implement lookbehinds, let alone unbounded lookbehinds.
I know there are workarounds for lookbehinds, but I can't seem to get the ones I've looked at to work.
I would rather not capture any characters aside from each tab, but if there's no other way, I could capture characters around the tabs in capture groups and add $1
, etc, to my replacement string.
Example test code
const text = `
\t\ta
\t b
\t \t c\td \te
`
const expected = `
a
b
c\td \te
`
// throws error in iOS, which does not support lookbehinds
// const regex = /(?<=^\s*)\t/gm;
const regex = /to-do/gm;
const result = text.replace(regex, ' ')
console.log(`Text: ${text}`)
console.log(`Expected: ${expected}`)
console.log(`Result: ${result}`)
console.log(JSON.stringify([ expected, result ], null, 2))
if (result === expected) {
console.info('Success!