turbocommons-ts
Version:
General purpose library that implements frequently used and generic software development tasks
545 lines (544 loc) • 29.5 kB
TypeScript
/**
* TurboCommons is a general purpose and cross-language library that implements frequently used and generic software development tasks.
*
* Website : -> https://turboframework.org/en/libs/turbocommons
* License : -> Licensed under the Apache License, Version 2.0. You may not use this file except in compliance with the License.
* License Url : -> http://www.apache.org/licenses/LICENSE-2.0
* CopyRight : -> Copyright 2015 Edertone Advanded Solutions (08211 Castellar del Vallès, Barcelona). http://www.edertone.com
*/
/**
* The most common string processing and modification utilities
*/
export declare class StringUtils {
/**
* Defines the sentence case format (Only the first character of the sentence is capitalised,except for
* proper nouns and other words which are required by a more specific rule to be capitalised).
* Generally equivalent to the baseline universal standard of formal English orthography
*/
static readonly FORMAT_SENTENCE_CASE = "FORMAT_SENTENCE_CASE";
/**
* Defines the start case format (The first character in all words capitalised and all the rest
* of the word lower case). It is also called Title Case
*/
static readonly FORMAT_START_CASE = "FORMAT_START_CASE";
/**
* Defines the all upper case format (All letters on a string written with Capital letters only)
*/
static readonly FORMAT_ALL_UPPER_CASE = "FORMAT_ALL_UPPER_CASE";
/**
* Defines the all lower case format (All letters on a string written with lower case letters only)
*/
static readonly FORMAT_ALL_LOWER_CASE = "FORMAT_ALL_LOWER_CASE";
/**
* Defines the first upper rest lower case format (All letters on a string written
* with lower case letters except the first one which is Capitalized)
*/
static readonly FORMAT_FIRST_UPPER_REST_LOWER = "FORMAT_FIRST_UPPER_REST_LOWER";
/**
* Defines the CamelCase format (the practice of writing compound words or phrases such that each
* word or abbreviation begins with a capital letter)
*/
static readonly FORMAT_CAMEL_CASE = "FORMAT_CAMEL_CASE";
/**
* Defines the UpperCamelCase format variation that writes first letter as upper case
*
* @see StringUtils.FORMAT_CAMEL_CASE
*/
static readonly FORMAT_UPPER_CAMEL_CASE = "FORMAT_UPPER_CAMEL_CASE";
/**
* Defines the lowerCamelCase format variation that writes first letter as lower case
*
* @see StringUtils.FORMAT_CAMEL_CASE
*/
static readonly FORMAT_LOWER_CAMEL_CASE = "FORMAT_LOWER_CAMEL_CASE";
/**
* Defines the snake_case format (the practice of writing compound words or phrases in which
* the elements are separated with one underscore character (_) and no spaces)
*/
static readonly FORMAT_SNAKE_CASE = "FORMAT_SNAKE_CASE";
/**
* Defines the FORMAT_UPPER_SNAKE_CASE format variation that writes all letters as upper case
*
* @see StringUtils.FORMAT_SNAKE_CASE
*/
static readonly FORMAT_UPPER_SNAKE_CASE = "FORMAT_UPPER_SNAKE_CASE";
/**
* Defines the lower_snake_case format variation that writes all letters as lower case
*
* @see StringUtils.FORMAT_SNAKE_CASE
*/
static readonly FORMAT_LOWER_SNAKE_CASE = "FORMAT_LOWER_SNAKE_CASE";
/**
* Tells if the given value is a string or not
*
* @param value A value to check
*
* @returns true if the given value is a string, false otherwise
*/
static isString(value: any): boolean;
/**
* Strictly check that the provided value is a string or throw an exception
*
* @param value A value to check
* @param valueName The name of the value to be shown at the beginning of the exception message
* @param errorMessage The rest of the exception message
*
* @throws Error If the check fails
*
* @return void
*/
static forceString(value: any, valueName?: string, errorMessage?: string): void;
/**
* Tells if the given string is a valid url or not
*
* @param value The value to check
*
* @return False in case the validation fails or true if validation succeeds.
*/
static isUrl(value: any): boolean;
/**
* Tells if a specified string is semantically empty, which applies to any string that is comprised of empty spaces, new line characters, tabulations or any other
* characters without a visually semantic value to the user.
*
* Example1: Following strings are considered as empty: " ", "", " \n\n\n", " \t\t\n"
* Example2: Following strings are not considered as empty: "hello", " a", " \n\nB"
*
* @param string The text to check
* @param emptyChars Custom list of strings that will be also considered as empty characters. For example, we can define 'NULL' and '_' as empty string values by setting this to ['NULL', '_']
*
* @return false if the string is not empty, true if the string contains non semantically valuable characters or any other characters defined as "empty" values
*/
static isEmpty(string: string, emptyChars?: string[]): boolean;
/**
* Checks if the given string starts with any of the specified values.
*
* @param str The string to check
* @param startingValues An array of strings that the input string should start with.
*
* @return True if the input string starts with any of the specified values, False otherwise.
*/
static isStartingWith(str: string, startingValues?: string[]): boolean;
/**
* Checks if a given string ends with any of the specified values.
*
* @param str The string to check
* @param endingValues An array of strings that the input string should end with.
*
* @return True if the input string ends with any of the specified values, False otherwise.
*/
static isEndingWith(str: string, endingValues?: string[]): boolean;
/**
* Strictly check that the provided value is a non empty string or throw an exception
*
* Uses the same criteria as the StringUtils.isEmpty() method
*
* @param value A value to check
* @param valueName The name of the value to be shown at the beginning of the exception message
* @param errorMessage The rest of the exception message
*
* @throws Error If the check fails
*
* @return void
*/
static forceNonEmptyString(value: any, valueName?: string, errorMessage?: string): void;
static isCamelCase(): void;
static isSnakeCase(): void;
/**
* Replace all occurrences of the search string with the replacement string
*
* @param string The string or array being searched and replaced on, otherwise known as the haystack.
* @param search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles
* (if we use an array, the order of replacement will be the same of the array: First element will be the first one to be replaced,
* second element the second, etc..)
* @param replacement The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
* @param count [optional] If passed and > 0, this will define the maximum number of replacements to perform
*
* @returns The string with all the replaced values
*/
static replace(string: string, search: string | string[], replacement: string | string[], count?: number): string;
/**
* This metod performs the same string replacement that replace() does, but instead of searching on a single string it will search on all the strings inside
* a given array or object.
*
* The search is totally recursive and will be performed inside any arrays, objects, and combination of any of them. Any value that is not a string which is
* found inside the provided structure will be ignored
*
* Method is non destructive: The provided structure is not altered, a copy is given
*
* @see StringUtils.replace
*
* @param string see StringUtils.replace
* @param search see StringUtils.replace
* @param replacement see StringUtils.replace
* @param count see StringUtils.replace
*
* @returns A copy of the provided object or array with all the values replaced on all its strings
*/
static replaceMulti(object: any, search: string | string[], replacement: string | string[], count?: number): any;
/**
* Remove whitespaces (or any custom set of characters) from both sides of a string
*
* @param string A string to process
* @param characters A set of characters that will be trimmed from both string sides. By default,
* empty space and new line characters are defined : " \n\r"
*
* @example: StringUtils.trim("abcXXabc", "abc") outputs "XX"
*
* @returns The trimmed string
*/
static trim(string: string, characters?: string): string;
/**
* Remove whitespaces (or any custom set of characters) from a string left side
*
* @param string A string to process
* @param characters A set of characters that will be trimmed from string left side. By default,
* empty space and new line characters are defined : " \n\r"
*
* @example: StringUtils.trimLeft("abcXXabc", "abc") outputs "XXabc"
*
* @returns The trimmed string
*/
static trimLeft(string: string, characters?: string): string;
/**
* Remove whitespaces (or any custom set of characters) from a string right side
*
* @param string A string to process
* @param characters A set of characters that will be trimmed from string right side. By default,
* empty space and new line characters are defined : " \n\r"
*
* @example: StringUtils.trimRight("abcXXabc", "abc") outputs "abcXX"
*
* @returns The trimmed string
*/
static trimRight(string: string, characters?: string): string;
/**
* Pad a string to a certain length with another string
*
* @param string The string to which we want to fill the empty spaces
* @param padLength The minimum length that we want for the resulting string to have
* @param padString The character or characters which we want to add to the string to match the target length
* @param mode LEFT to append the padString to the left of the string, RIGHT to append the padString to the right of the string
*
* @returns The padded string
*/
static pad(string: string, padLength: number, padString?: string, mode?: string): string;
/**
* Count the number of times a string is found inside another string
*
* @param string The string where we want to search
* @param findMe The string that we want to look for
*
* @returns The number of times that findMe appears on string
*/
static countStringOccurences(string: string, findMe: string): number;
/**
* Count the number of characters that match the given letter case on the given string
*
* @param string The string which case matching characters will be counted
* @param letterCase Defines which letter case are we looking for: StringUtils.FORMAT_ALL_UPPER_CASE or
* StringUtils.FORMAT_ALL_LOWER_CASE
*
* @return The number of characters with the specified letter case that are present on the string
*/
static countByCase(string: string, letterCase?: string): number;
/**
* Count the number of words that exist on the given string
*
* @param string The string which words will be counted
* @param wordSeparator ' ' by default. The character that is considered as the word sepparator
*
* @returns The number of words (elements divided by the wordSeparator value) that are present on the string
*/
static countWords(string: string, wordSeparator?: string): number;
/**
* Given a string with a list of elements separated by '/' or '\' that represent some arbitrary path structure,
* this method will return the number of elements that are listed on the path.
*
* @example "c:\\" -> results in 1
* "//folder/folder2/folder3/file.txt" -> results in 4
*
* @param path A string containing some arbitrary path.
*
* @return The number of elements that are listed on the provided path
*/
static countPathElements(path: string): number;
/**
* Method that limits the length of a string and optionally appends informative characters like ' ...'
* to inform that the original string was longer.
*
* @param string String to limit
* @param limit Max number of characters
* @param limiterString If the specified text exceeds the specified limit, the value of this parameter will be added to the end of the result. The value is ' ...' by default.
*
* @returns The specified string but limited in length if necessary. Final result will never exceed the specified limit, also with the limiterString appended.
*/
static limitLen(string: string, limit?: number, limiterString?: string): string;
/**
* Extracts the domain name from a given url (excluding subdomain).
* For example: http://subdomain.google.com/test/ will result in 'google.com'
*
* @param url A string containing an URL
*
* @returns The domain from the given string (excluding the subdomain if exists)
*/
static getDomainFromUrl(url: string): any;
/**
* Extracts the hostname (domain + subdomain) from a given url.
* For example: http://subdomain.google.com/test/ will result in 'subdomain.google.com'
*
* @param url A string containing an URL
*
* @returns The domain and subdomain from the given string (subdomain.domain.com)
*/
static getHostNameFromUrl(url: string): string;
/**
* Extracts all the lines from the given string and outputs an array with each line as an element.
* It does not matter which line separator's been used (\n, \r, Windows, linux...). All source lines will be correctly extracted.
*
* @param string Text containing one or more lines that will be converted to an array with each line on a different element.
* @param filters One or more regular expressions that will be used to filter unwanted lines. Lines that match any of the
* filters will be excluded from the result. By default, all empty lines are ignored (those containing only newline, blank, tabulators, etc..).
*
* @returns A list with all the string lines sepparated as different array elements.
*/
static getLines(string: string, filters?: RegExp[]): string[];
static getKeyWords(): void;
/**
* Given a string with a list of elements separated by '/' or '\' that represent some arbitrary path structure,
* this method will format the specified path and remove the number of requested path elements (from its right
* side) and return the path without that elements.
*
* This method can be used with Operating system file paths, urls, or any other string that uses the 'slash separated'
* format to encode a path.
*
* @example "//folder/folder2/folder3/file.txt" -> results in "/folder/folder2/folder3" if elementsToRemove = 1<br>
* "//folder/folder2\folder3\file.txt" -> results in "/folder/folder2" if elementsToRemove = 2
*
* @see StringUtils.formatPath
*
* @param path A string containing some arbitrary path.
* @param elementsToRemove (one by default) The number of elements that we want to remove from the right side of the path.
* @param separator The character to use as the element divider for the returned path. Only slash '/' or backslash '\' are allowed.
*
* @return The received path without the specified number of elements and correctly formatted
*/
static getPath(path: string, elementsToRemove?: number, separator?: string): string;
/**
* Given a string with a list of elements separated by '/' or '\' that represent some arbitrary path structure,
* this method will return the element that is located at the requested position. If no position is defined,
* by default the last element of the path will be returned (the most to the right one).
*
* This method can be used with Operating system file paths, urls, or any other string that uses the 'slash separated'
* format to encode a path.
*
* @example "//folder/folder2/folder3/file.txt" -> results in "file.txt" if (-1) position is defined<br>
* "//folder/folder2\folder3\file.txt" -> results in "folder" if position 0 is defined<br>
* "//folder/folder2\folder3\file.txt" -> results in "folder3" if position 2 is defined<br>
* "//folder/folder2\folder3\file.txt" -> results in "folder3" if position -2 is defined<br>
* "//folder/folder2\folder3\file.txt" -> results in "folder2" if position -3 is defined
*
* @param path A string containing some arbitrary path.
* @param position The index for the element that we want to extract from the path. Positive values will get path elements
* starting from the left side, being 0 the first most to the left one. Negative values will get path elements starting from
* the right side, being -1 the last path element (or the first most to the right one).
* If not specified, the last one will be returned.
*
* @return The element at the specified path position or the last one if no position is defined
*/
static getPathElement(path: string, position?: number): string;
/**
* This method works in the same way as getPathElement but it also removes the extension part from the result
* if it has any.
*
* @example "//folder/folder2/folder3/file.txt" -> results in "file" if position = -1. Notice that ".txt" extension is removed<br>
* "//folder/folder2\folder3\file.txt" -> results in "folder3" if position = 2. "folder3" has no extension so it does not get modified.
*
* @see StringUtils.getPathElement
*
* @param path A string containing some arbitrary path.
* @param position The index for the element that we want to extract from the path. If not specified, the
* last one will be returned.
* @param extensionSeparator The character to be used as the extension separator. The most commonly used is '.'
*
* @return The element at the specified path position with it's extension removed or the last one if no position is defined
*/
static getPathElementWithoutExt(path: string, position?: number, extensionSeparator?: string): string;
/**
* This method works in the same way as getPathElement but it only gives the element extension if it has any.
*
* @example "//folder/folder2/folder3/file.txt" -> results in "txt" if position = -1. Notice that extension without separator character is returned<br>
* "//folder/folder2\folder3\file.txt" -> results in "folder3" if position = 2. "folder3" has no extension so it does not get modified.
*
* @see StringUtils.getPathElement
*
* @param path A string containing some arbitrary path.
* @param position The index for the element extension that we want to extract from the path. If not specified, the
* last one will be returned.
* @param extensionSeparator The character to be used as the extension separator. The most commonly used is '.'
*
* @return The extension from the element at the specified path position or the extension from the last one if no position is defined
*/
static getPathExtension(path: string, position?: number, extensionSeparator?: string): string;
/**
* Given an internet URL, this method extracts only the scheme part.
* Example: "http://google.com" -> results in "http"
*
* @see StringUtils.formatUrl
*
* @param url A valid internet url
*
* @returns ('ftp', 'http', ...) if the url is valid or '' if the url is invalid
*/
static getSchemeFromUrl(url: string): string;
/**
* Changes the letter case for the given string to the specified format.
*
* @param string A string that will be processed to match the specified case format.
* @param format The format to which the given string will be converted. Possible values are defined as
* StringUtils constants that start with <b>FORMAT_</b>, like: StringUtils.FORMAT_ALL_UPPER_CASE
*
* @see StringUtils.FORMAT_SENTENCE_CASE
* @see StringUtils.FORMAT_START_CASE
* @see StringUtils.FORMAT_ALL_UPPER_CASE
* @see StringUtils.FORMAT_ALL_LOWER_CASE
* @see StringUtils.FORMAT_FIRST_UPPER_REST_LOWER
* @see StringUtils.FORMAT_CAMEL_CASE
* @see StringUtils.FORMAT_UPPER_CAMEL_CASE
* @see StringUtils.FORMAT_LOWER_CAMEL_CASE
* @see StringUtils.FORMAT_SNAKE_CASE
* @see StringUtils.FORMAT_UPPER_SNAKE_CASE
* @see StringUtils.FORMAT_LOWER_SNAKE_CASE
*
* @returns The given string converted to the specified case format.
*/
static formatCase(string: string, format: string): string;
/**
* Given a string with a list of elements separated by '/' or '\' that represent some kind of unformatted path,
* this method will process it to get a standarized one by applying the following rules:
*
* - Duplicate separator characters will be removed: "a\\\b\\c" will become "a/b/c"
* - All separator characters will be unified to the same one: "a\b/c\d" will become "a/b/c/d"
* - No trailing separator will exist: "a\b\c\" will become "a\b\c"
*
* NOTE: This method only applies format to the received string. It does not check if the path is a real
* location or a valid url, and won't also fail if the received path contains strange characters or is invalid.
*
* @param path A raw path to be formatted
* @param separator The character to use as the element divider. Only slash '/' or backslash '\' are allowed.
*
* @return The correctly formatted path without any trailing separator
*/
static formatPath(path: any, separator?: string): string;
/**
* Given a raw string containing an internet URL, this method will process it to obtain a URL that is 100% format valid.
*
* A Uniform Resource Locator (URL), commonly informally termed a web address is a reference to a web resource that specifies
* its location on a computer network and a mechanism for retrieving it. URLs occur most commonly to reference web pages (http),
* but are also used for file transfer (ftp), email (mailto), database access (JDBC), and many other applications.
*
* Every HTTP URL conforms to the syntax of a generic URI. A generic URI is of the form: scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
*
* @see https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax
*
* @returns The formated url string or the original string if it was not a valid url
*/
static formatUrl(url: string): string;
/**
* Full text search is the official name for the process of searching on a big text content based on a string containing some text to find.
* This method will process a text so it removes all the accents and non alphanumerical characters that are not usefull for searching on strings,
* convert everything to lower case and remove empty spaces.
* To perform the search it is important that both search and searched strings are standarized the same way, to maximize possible matches.
*
* @param string String to process
* @param wordSeparator The character that will be treated as the word separator. By default it is the empty space character ' '
*
* @return The resulting string
*/
static formatForFullTextSearch(string: string, wordSeparator?: string): string;
/**
* Compares two strings and gives the number of character replacements that must be performed to convert one
* of the strings into the other. A very useful method to use in fuzzy text searches where we want to look for
* similar texts. This method uses the Levenshtein method for the comparison:
*
* The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete
* to transform string1 into string2. The complexity of the algorithm is O(m*n), where n and m are the length
* of string1 and string2.
*
* @example "aha" and "aba" will output 1 cause we need to change the h for a b to transform one string into another.
*
* @param string1 The first string to compare
* @param string2 The second string to compare
*
* @return The number of characters to replace to convert $string1 into $string2 where 0 means both strings are the same.
* The higher the result, the more different the strings are.
*/
static compareByLevenshtein(string1: string, string2: string): number;
/**
* Compares the percentage of similarity between two strings, based on the Levenshtein method. A very useful method
* to use in fuzzy text searches where we want to look for similar texts.
*
* @param string1 The first string to compare
* @param string2 The second string to compare
*
* @return A number between 0 and 100, being 100 if both strings are the same and 0 if both strings are totally different
*/
static compareSimilarityPercent(string1: string, string2: string): number;
/**
* Generate a path string from an array of elements.
*
* @param elements An array of elements that will be used to form the path.
* @param separator An optional separator that will be used to join the elements in the path. Defaults to `/`.
*
* @return A string representing the path formed from the given elements.
*/
static generatePath(elements: string[], separator?: string): string;
/**
* Generates a random string with the specified length and options
*
* @param minLength Specify the minimum possible length for the generated string
* @param maxLength Specify the maximum possible length for the generated string
* @param charSet Defines the list of possible characters to be generated. Each element of charSet must be a string containing
* the possible characters like 'a1kjuhAO' or a range like 'a-z', 'A-D', '0-5', ... etc.
* Note that - character must be escaped \- when not specified as part of a range.
* Default charset is alphanumeric ['0-9', 'a-z', 'A-Z']
*
* @return A randomly generated string
*/
static generateRandom(minLength: number, maxLength: number, charSet?: string[]): string;
static findMostSimilarString(): void;
static findMostSimilarStringIndex(): void;
static removeNewLineCharacters(): void;
/**
* Converts all accent characters to ASCII characters on a given string.<br>
* This method is based on a stack overflow implementation called removeDiacritics
*
* @see http://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
*
* @param string Text from which accents must be cleaned
*
* @returns The given string with all accent and diacritics replaced by the respective ASCII characters.
*/
static removeAccents(string: string): string;
static removeWordsShorterThan(): void;
static removeWordsLongerThan(): void;
static removeUrls(): void;
static removeHtmlCode(): void;
/**
* Remove all duplicate consecutive fragments from the provided string and leave only one occurence
*
* @param string The string to process
* @param set A list with the fragments that will be removed when found consecutive. If this value is
* an empty array, all duplicate consecutive characters will be deleted.
* We can pass here words or special characters like "\n"
*
* @example If we want to remove all duplicate consecutive empty spaces,
* we will call removeSameConsecutive('string', [' '])
* @example If we want to remove all duplicate consecutive new line characters,
* we will call removeSameConsecutive("string\n\n\nstring", ["\n"])
* @example If we want to remove all duplicate "hello" words, we will call
* removeSameConsecutive('hellohellohellohello', ['hello'])
*
* @returns The string with a maximum of one consecutive sequence for all those matching the provided set
*/
static removeSameConsecutive(string: string, set?: string[]): string;
}