I have this regex (?<![\n])[\n]{1}(?![\n]) in my Javascript code, and as I understand Safari just doesn't support negative look behinds.
What I need to do is replace all \n that are not surrounded by other \n and replace them with a string.
Can someone please help me figure out how to write that Regex so that it is usable in Safari?
Thank you.
You could capture either the start of the string or a non whitespace character in group 1.
Then match a single newline, and assert not a newline to the right.
In the replacement use the capture group followed by your replacement string $1[replacement]
Note that you don't need the square brackets around the newline, and you can omit {1}
(\S|^)\n(?!\n)
const regex = /(\S|^)\n(?!\n)/g;
const str = `
this is a
this is b
this is c
d
test
test
test
test
`;
const result = str.replace(regex,`$1[replacement]`);
console.log(result);
Your pattern with the lookbehind (if supported):
const regex = /(?<!\n)\n(?!\n)/g;
const str = `
this is a
this is b
this is c
d
test
test
test
test
`;
`[replacement]`
const result = str.replace(regex,`[replacement]`);
console.log(result);
Use
text.replace(/(\n)?\n(?!\n)/g, function(p,q) {
return q === undefined ? "<a string>":p
})
JS code:
var text = "a\nb\n\nc"
console.log(
text.replace(/(\n)?\n(?!\n)/g, function(p,q) {
return q === undefined ? "<a string>":p
}))