const regex = /(?<sup_all>
(?:
(?<!\\)\^
(?<sup_text>
(?>\\[\^[:blank:]\h]|[^\^[:blank:]\h\v])*+
)
(?<!\\)\^
)
|
(?: # or the Microsoft way. Beurk
\<sup\>
(?<sup_text>
((?!\v).)+
)
\<\/sup\>
)
)/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?<sup_all>
(?:
(?<!\\\\)\\^
(?<sup_text>
(?>\\\\[\\^[:blank:]\\h]|[^\\^[:blank:]\\h\\v])*+
)
(?<!\\\\)\\^
)
|
(?: # or the Microsoft way. Beurk
\\<sup\\>
(?<sup_text>
((?!\\v).)+
)
\\<\\\/sup\\>
)
)', 'g')
const str = `2^10^ is 1024.
Space is not allowed:
P^a cat^
But it's ok if it is escaped
P^a\\ cat^
Line break is a no-no, even escaped
P^a\\
cat^
Hmm <sup>This is a Microsoft superscript!</sup>
H^2^0
text^a\\ superscript^
`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions