budibase/packages/string-templates/src/utilities.ts

64 lines
1.7 KiB
TypeScript
Raw Normal View History

const ALPHA_NUMERIC_REGEX = /^[A-Za-z0-9]+$/g
2024-02-21 19:42:15 +01:00
export const FIND_HBS_REGEX = /{{([^{].*?)}}/g
export const FIND_ANY_HBS_REGEX = /{?{{([^{].*?)}}}?/g
export const FIND_TRIPLE_HBS_REGEX = /{{{([^{].*?)}}}/g
2024-02-21 19:42:15 +01:00
export const isBackendService = () => {
return typeof window === "undefined"
}
2024-02-21 19:42:15 +01:00
export const isJSAllowed = () => {
return process && !process.env.NO_JS
}
// originally this could be done with a single regex using look behinds
// but safari does not support this feature
// original regex: /(?<!{){{[^{}]+}}(?!})/g
2024-02-21 19:42:15 +01:00
export const findDoubleHbsInstances = string => {
let copied = string
2024-02-21 19:57:05 +01:00
const doubleRegex = new RegExp(FIND_HBS_REGEX)
const regex = new RegExp(FIND_TRIPLE_HBS_REGEX)
const tripleMatches = copied.match(regex)
// remove triple braces
if (tripleMatches) {
tripleMatches.forEach(match => {
copied = copied.replace(match, "")
})
}
const doubleMatches = copied.match(doubleRegex)
return doubleMatches ? doubleMatches : []
}
2024-02-21 19:42:15 +01:00
export const isAlphaNumeric = char => {
return char.match(ALPHA_NUMERIC_REGEX)
}
2024-02-21 19:42:15 +01:00
export const swapStrings = (string, start, length, swap) => {
return string.slice(0, start) + swap + string.slice(start + length)
}
2024-02-21 19:42:15 +01:00
export const removeHandlebarsStatements = (
string,
replacement = "Invalid binding"
) => {
2024-02-21 19:57:05 +01:00
let regexp = new RegExp(FIND_HBS_REGEX)
let matches = string.match(regexp)
if (matches == null) {
return string
}
for (let match of matches) {
const idx = string.indexOf(match)
2024-02-21 19:57:05 +01:00
string = swapStrings(string, idx, match.length, replacement)
}
return string
}
2024-02-21 19:42:15 +01:00
export const btoa = plainText => {
return Buffer.from(plainText, "utf-8").toString("base64")
}
2024-02-21 19:42:15 +01:00
export const atob = base64 => {
return Buffer.from(base64, "base64").toString("utf-8")
}