Javascript Regexes
For about a month now, Iām playing with regexes with my new project !
To replace strings that have dashes as separator with uppercase (kebab case to camel case)
let myString = "my-super-string"; // Expected Output: mySuperString
myString.replace(/-([a-zA-Z])/g, (match, group1) => group1.toUpperCase());
Prints:
'mySuperString'
Regexes for Images (HTML and Markdown)
export const imageDataRe: RegExp =
/<img src="data:image\/(.*?);base64,(.*?)"(.*?)>/;
export const imageBlobRe: RegExp = /<img src="blob:(.*?)">/g;
export const imageBlobHttpsHttpRe: RegExp =
/<img src="[blob:\|https:\|http:](.*?)">/g;
export const imageBlobHttpRe: RegExp = /<img src="blob:http:\/\/.*?\/(.*?)">/;
export const imageMarkdownRe: RegExp = /^\!\[(.*?)\]\((.*?)\)/;
export const imageLocalRe: RegExp =
/<img src="(?!http)(.*?)" alt="(.*?)" width="(.*?)">/;
export const imageSrcRe: RegExp = /<img src="(.*?)"(.*?)>/g;
export const imageDataOnlyRe: RegExp = /data:image\/(.*?);base64,(.*?)$/;
Escaping Regex Function
export function sanitizeRegex(input: string) {
// Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions#escaping
return input.replace(/[\/.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
Function to verify if a string contains an image
export function checkImage(html: string): boolean {
// On macos it uses the blob: approach
// on windows it uses the data: approach
if (
html.match(/<img src="blob:.*"/g) ||
html.match(/<img src="data:.*"/g) ||
html.match(/<img src="https?:.*"/g)
) {
return true;
}
return false;
}