SpaceNinjaServer/src/helpers/stringHelpers.ts
Sainan 49edebc1eb
All checks were successful
Build / build (20) (push) Successful in 43s
Build / build (18) (push) Successful in 1m16s
Build Docker image / docker (push) Successful in 35s
Build / build (22) (push) Successful in 1m19s
chore: fix controllers exporting non-RequestHandler things (#1468)
I'm surprised JavaScript allows circular includes, but they still don't feel good.

Reviewed-on: #1468
Co-authored-by: Sainan <63328889+Sainan@users.noreply.github.com>
Co-committed-by: Sainan <63328889+Sainan@users.noreply.github.com>
2025-04-05 06:52:35 -07:00

57 lines
1.9 KiB
TypeScript

import { JSONParse } from "json-with-bigint";
export const getJSONfromString = <T>(str: string): T => {
const jsonSubstring = str.substring(0, str.lastIndexOf("}") + 1);
return JSONParse<T>(jsonSubstring);
};
export const getSubstringFromKeyword = (str: string, keyword: string): string => {
const index = str.indexOf(keyword);
if (index == -1) {
throw new Error(`keyword ${keyword} not found in string ${str}`);
}
return str.substring(index);
};
export const getSubstringFromKeywordToKeyword = (str: string, keywordBegin: string, keywordEnd: string): string => {
const beginIndex = str.lastIndexOf(keywordBegin) + 1;
const endIndex = str.indexOf(keywordEnd);
return str.substring(beginIndex, endIndex + 1);
};
export const getIndexAfter = (str: string, searchWord: string): number => {
const index = str.indexOf(searchWord);
if (index === -1) {
return -1;
}
return index + searchWord.length;
};
// This is FNV1a-32 except operating under modulus 2^31 because JavaScript is stinky and likes producing negative integers out of nowhere.
export const catBreadHash = (name: string): number => {
let hash = 2166136261;
for (let i = 0; i != name.length; ++i) {
hash = (hash ^ name.charCodeAt(i)) & 0x7fffffff;
hash = (hash * 16777619) & 0x7fffffff;
}
return hash;
};
export const regexEscape = (str: string): string => {
str = str.split(".").join("\\.");
str = str.split("\\").join("\\\\");
str = str.split("[").join("\\[");
str = str.split("]").join("\\]");
str = str.split("+").join("\\+");
str = str.split("*").join("\\*");
str = str.split("$").join("\\$");
str = str.split("^").join("\\^");
str = str.split("?").join("\\?");
str = str.split("|").join("\\|");
str = str.split("(").join("\\(");
str = str.split(")").join("\\)");
str = str.split("{").join("\\{");
str = str.split("}").join("\\}");
return str;
};