Skip to content

Instantly share code, notes, and snippets.

@hansSchall
Last active August 28, 2022 15:44
Show Gist options
  • Save hansSchall/a09ded22cd8b9326d8802b2d95e1d667 to your computer and use it in GitHub Desktop.
Save hansSchall/a09ded22cd8b9326d8802b2d95e1d667 to your computer and use it in GitHub Desktop.
How to store a string[] as string

How to store a string array as string

A little helper function:

export function escapeRegExp(str: string) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

encode ...

export function joincomma(splitted: string[], char: string = ",") {
    return splitted.map(_ => _.replace(/\\/g, "\\\\").split(char).join("\\" + char)).join(char);
}

... and decode again

export function splitcomma(joined: string, char: string = ",") {
    return joined.split(new RegExp(`(?<!\\\\)${escapeRegExp(char)}`, "g")).map(_ => _.replace(/\\(?!\\)/g, "").replace(/\\\\/g, "\\"))
}
export function escapeRegExp(str: string) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
export function joincomma(splitted: string[], char: string = ",") {
return splitted.map(_ => _.replace(/\\/g, "\\\\").split(char).join("\\" + char)).join(char);
}
export function splitcomma(joined: string, char: string = ",") {
return joined.split(new RegExp(`(?<!\\\\)${escapeRegExp(char)}`, "g")).map(_ => _.replace(/\\(?!\\)/g, "").replace(/\\\\/g, "\\"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment