From 2e580a50242686316f40aaf74d7d1bfc8434e972 Mon Sep 17 00:00:00 2001 From: Angus MacDonald Date: Thu, 26 Nov 2020 21:06:25 -0600 Subject: [PATCH] Add lstrip, rstrip and trim string functions --- src/string/stringf.ts | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/string/stringf.ts b/src/string/stringf.ts index 029895341b..0f6785db20 100644 --- a/src/string/stringf.ts +++ b/src/string/stringf.ts @@ -71,4 +71,35 @@ export class stringf { static numeric(x:string):string { return x && x.replace(/[^0-9\.]/gi,''); } -} \ No newline at end of file + + /** + * Strip characters from the left side of a string + */ + static lstrip(value: string, characters: string[] = [' ']): string { + const charSet = new Set(characters); + let startIndex: number = 0; + while (charSet.has(value[startIndex])) { + startIndex++; + } + return value.slice(startIndex); + } + + /** + * Strip characters from the right side of a string + */ + static rstrip(value: string, characters: string[] = [' ']): string { + const charSet = new Set(characters); + let endIndex: number = value.length; + while (charSet.has(value[endIndex - 1])) { + endIndex--; + } + return value.slice(0, endIndex); + } + + /** + * Strip characters from the left and right side of a string + */ + static trim(value: string, characters: string[] = [' ']): string { + return stringf.lstrip(stringf.rstrip(value, characters), characters); + } +}