diff options
author | lonkaars <loek@pipeframe.xyz> | 2023-06-29 14:25:29 +0200 |
---|---|---|
committer | lonkaars <loek@pipeframe.xyz> | 2023-06-29 14:25:29 +0200 |
commit | 3f7ae147fb969db479c10eaa871a840a30e281b3 (patch) | |
tree | 2e99c35f59f0effb260c26118e9edf3199bb8de7 /util/string.ts | |
parent | c998e1c0477d51c886f9e4246e102dec4d7ef8dd (diff) |
http proof of concept api
Diffstat (limited to 'util/string.ts')
-rw-r--r-- | util/string.ts | 41 |
1 files changed, 37 insertions, 4 deletions
diff --git a/util/string.ts b/util/string.ts index e0cc5eb..16d8f0a 100644 --- a/util/string.ts +++ b/util/string.ts @@ -4,12 +4,33 @@ import JapaneseString from "../language/japanese.ts"; declare global { /** @summary extended String prototype functions */ interface String { + /** @summary get UnicodeRange for character at index 0 */ range(): UnicodeRange; + /** @summary create a RangeTally object for counting used unicode ranges in string */ rangeTally(): RangeTally; + /** @summary get JapaneseString from this string */ jp(): JapaneseString; + /** @summary parse concatenated tag string to TokenTags */ parseTags(): TokenTags; + + /** + * @summary Remove all instances of a substring in a string, using a regular expression or search string + * @param searchValue A string to search for + */ + removeAll(searchValue: string | RegExp): string; + + /** + * @summary parse string as JSON, with optional fallback value + * + * fallback is undefined by default. if fallback is specified, it will be + * returned if JSON.parse throws any error. if fallback is not specified, + * no errors will be caught. + * + * @argument fallback return this value if parsing fails + */ + json(fallback?: any): any; } } @@ -27,7 +48,6 @@ export enum UnicodeRange { type RangeTally = Record<UnicodeRange, number>; -/** @summary get UnicodeRange for character at index 0 */ String.prototype.range = function() { var code = this.charCodeAt(0); @@ -46,20 +66,33 @@ String.prototype.range = function() { return UnicodeRange.Unknown; } -/** @summary create a RangeTally object for counting used unicode ranges in string */ String.prototype.rangeTally = function() { var tally = Object.keys(UnicodeRange).reduce((a: any,c) => (a[c] = 0, a), {}) as RangeTally; for (var char of this) tally[char.range()]++; return tally; }; -/** @summary get JapaneseString from this string */ String.prototype.jp = function() { return new JapaneseString(this); } -/** @summary parse concatenated tag string to TokenTags */ String.prototype.parseTags = function() { return parseTags(this as string); } +String.prototype.removeAll = function(searchValue: string | RegExp) { + return this.replaceAll(searchValue, ""); +} + +String.prototype.json = function(fallback?: any) { + if (fallback) { + try { + return JSON.parse(this as string); + } catch { + return fallback; + } + } else { + return JSON.parse(this as string); + } +} + |