Options
All
  • Public
  • Public/Protected
  • All
Menu

The most common string processing and modification utilities

Hierarchy

  • StringUtils

Index

Properties

Static Readonly FORMAT_ALL_LOWER_CASE

FORMAT_ALL_LOWER_CASE: "FORMAT_ALL_LOWER_CASE" = "FORMAT_ALL_LOWER_CASE"

Defines the all lower case format (All letters on a string written with lower case letters only)

Static Readonly FORMAT_ALL_UPPER_CASE

FORMAT_ALL_UPPER_CASE: "FORMAT_ALL_UPPER_CASE" = "FORMAT_ALL_UPPER_CASE"

Defines the all upper case format (All letters on a string written with Capital letters only)

Static Readonly FORMAT_CAMEL_CASE

FORMAT_CAMEL_CASE: "FORMAT_CAMEL_CASE" = "FORMAT_CAMEL_CASE"

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_FIRST_UPPER_REST_LOWER

FORMAT_FIRST_UPPER_REST_LOWER: "FORMAT_FIRST_UPPER_REST_LOWER" = "FORMAT_FIRST_UPPER_REST_LOWER"

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_LOWER_CAMEL_CASE

FORMAT_LOWER_CAMEL_CASE: "FORMAT_LOWER_CAMEL_CASE" = "FORMAT_LOWER_CAMEL_CASE"

Defines the lowerCamelCase format variation that writes first letter as lower case

see

StringUtils.FORMAT_CAMEL_CASE

Static Readonly FORMAT_LOWER_SNAKE_CASE

FORMAT_LOWER_SNAKE_CASE: "FORMAT_LOWER_SNAKE_CASE" = "FORMAT_LOWER_SNAKE_CASE"

Defines the lower_snake_case format variation that writes all letters as lower case

see

StringUtils.FORMAT_SNAKE_CASE

Static Readonly FORMAT_SENTENCE_CASE

FORMAT_SENTENCE_CASE: "FORMAT_SENTENCE_CASE" = "FORMAT_SENTENCE_CASE"

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_SNAKE_CASE

FORMAT_SNAKE_CASE: "FORMAT_SNAKE_CASE" = "FORMAT_SNAKE_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_START_CASE

FORMAT_START_CASE: "FORMAT_START_CASE" = "FORMAT_START_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_UPPER_CAMEL_CASE

FORMAT_UPPER_CAMEL_CASE: "FORMAT_UPPER_CAMEL_CASE" = "FORMAT_UPPER_CAMEL_CASE"

Defines the UpperCamelCase format variation that writes first letter as upper case

see

StringUtils.FORMAT_CAMEL_CASE

Static Readonly FORMAT_UPPER_SNAKE_CASE

FORMAT_UPPER_SNAKE_CASE: "FORMAT_UPPER_SNAKE_CASE" = "FORMAT_UPPER_SNAKE_CASE"

Defines the FORMAT_UPPER_SNAKE_CASE format variation that writes all letters as upper case

see

StringUtils.FORMAT_SNAKE_CASE

Methods

Static compareByLevenshtein

  • compareByLevenshtein(string1: string, string2: string): number
  • 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.

    Parameters

    • string1: string

      The first string to compare

    • string2: string

      The second string to compare

    Returns number

    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 compareSimilarityPercent

  • compareSimilarityPercent(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.

    Parameters

    • string1: string

      The first string to compare

    • string2: string

      The second string to compare

    Returns number

    A number between 0 and 100, being 100 if both strings are the same and 0 if both strings are totally different

Static countByCase

  • countByCase(string: string, letterCase?: string): number
  • Count the number of characters that match the given letter case on the given string

    Parameters

    • string: string

      The string which case matching characters will be counted

    • Default value letterCase: string = StringUtils.FORMAT_ALL_UPPER_CASE

      Defines which letter case are we looking for: StringUtils.FORMAT_ALL_UPPER_CASE or StringUtils.FORMAT_ALL_LOWER_CASE

    Returns number

    The number of characters with the specified letter case that are present on the string

Static countPathElements

  • countPathElements(path: 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

    Parameters

    • path: string

      A string containing some arbitrary path.

    Returns number

    The number of elements that are listed on the provided path

Static countStringOccurences

  • countStringOccurences(string: string, findMe: string): number
  • Count the number of times a string is found inside another string

    Parameters

    • string: string

      The string where we want to search

    • findMe: string

      The string that we want to look for

    Returns number

    The number of times that findMe appears on string

Static countWords

  • countWords(string: string, wordSeparator?: string): number
  • Count the number of words that exist on the given string

    Parameters

    • string: string

      The string which words will be counted

    • Default value wordSeparator: string = " "

      ' ' by default. The character that is considered as the word sepparator

    Returns number

    The number of words (elements divided by the wordSeparator value) that are present on the string

Static findMostSimilarString

  • findMostSimilarString(): void
  • Returns void

Static findMostSimilarStringIndex

  • findMostSimilarStringIndex(): void
  • Returns void

Static forceNonEmptyString

  • forceNonEmptyString(value: any, valueName?: string, errorMessage?: string): void
  • Strictly check that the provided value is a non empty string or throw an exception

    Uses the same criteria as the StringUtils.isEmpty() method

    throws

    Error If the check fails

    Parameters

    • value: any

      A value to check

    • Default value valueName: string = ""

      The name of the value to be shown at the beginning of the exception message

    • Default value errorMessage: string = "must be a non empty string"

      The rest of the exception message

    Returns void

    void

Static forceString

  • forceString(value: any, valueName?: string, errorMessage?: string): void
  • Strictly check that the provided value is a string or throw an exception

    throws

    Error If the check fails

    Parameters

    • value: any

      A value to check

    • Default value valueName: string = ""

      The name of the value to be shown at the beginning of the exception message

    • Default value errorMessage: string = "must be a string"

      The rest of the exception message

    Returns void

    void

Static formatCase

  • formatCase(string: string, format: string): string
  • Changes the letter case for the given string to the specified format.

    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

    Parameters

    • string: string

      A string that will be processed to match the specified case format.

    • format: string

      The format to which the given string will be converted. Possible values are defined as StringUtils constants that start with FORMAT_, like: StringUtils.FORMAT_ALL_UPPER_CASE

    Returns string

    The given string converted to the specified case format.

Static formatForFullTextSearch

  • formatForFullTextSearch(string: string, wordSeparator?: 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.

    Parameters

    • string: string

      String to process

    • Default value wordSeparator: string = " "

      The character that will be treated as the word separator. By default it is the empty space character ' '

    Returns string

    The resulting string

Static formatPath

  • formatPath(path: any, separator?: 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.

    Parameters

    • path: any

      A raw path to be formatted

    • Default value separator: string = "/"

      The character to use as the element divider. Only slash '/' or backslash '' are allowed.

    Returns string

    The correctly formatted path without any trailing separator

Static formatUrl

  • formatUrl(url: 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

    Parameters

    • url: string

    Returns string

    The formated url string or the original string if it was not a valid url

Static generatePath

  • generatePath(elements: string[], separator?: string): string
  • Generate a path string from an array of elements.

    Parameters

    • elements: string[]

      An array of elements that will be used to form the path.

    • Default value separator: string = ""

      An optional separator that will be used to join the elements in the path. Defaults to /.

    Returns string

    A string representing the path formed from the given elements.

Static generateRandom

  • generateRandom(minLength: number, maxLength: number, charSet?: string[]): string
  • Generates a random string with the specified length and options

    Parameters

    • minLength: number

      Specify the minimum possible length for the generated string

    • maxLength: number

      Specify the maximum possible length for the generated string

    • Default value charSet: string[] = ['0-9', 'a-z', 'A-Z']

      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']

    Returns string

    A randomly generated string

Static getDomainFromUrl

  • getDomainFromUrl(url: string): any
  • Extracts the domain name from a given url (excluding subdomain). For example: http://subdomain.google.com/test/ will result in 'google.com'

    Parameters

    • url: string

      A string containing an URL

    Returns any

    The domain from the given string (excluding the subdomain if exists)

Static getHostNameFromUrl

  • getHostNameFromUrl(url: string): string
  • Extracts the hostname (domain + subdomain) from a given url. For example: http://subdomain.google.com/test/ will result in 'subdomain.google.com'

    Parameters

    • url: string

      A string containing an URL

    Returns string

    The domain and subdomain from the given string (subdomain.domain.com)

Static getKeyWords

  • getKeyWords(): void
  • Returns void

Static getLines

  • getLines(string: string, filters?: RegExp[]): 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.

    Parameters

    • string: string

      Text containing one or more lines that will be converted to an array with each line on a different element.

    • Default value filters: RegExp[] = [/\s+/g]

      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 string[]

    A list with all the string lines sepparated as different array elements.

Static getPath

  • 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 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
    "//folder/folder2\folder3\file.txt" -> results in "/folder/folder2" if elementsToRemove = 2

    see

    StringUtils.formatPath

    Parameters

    • path: string

      A string containing some arbitrary path.

    • Default value elementsToRemove: number = 1

      (one by default) The number of elements that we want to remove from the right side of the path.

    • Default value separator: string = "/"

      The character to use as the element divider for the returned path. Only slash '/' or backslash '' are allowed.

    Returns string

    The received path without the specified number of elements and correctly formatted

Static getPathElement

  • getPathElement(path: string, position?: number): 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
    "//folder/folder2\folder3\file.txt" -> results in "folder" if position 0 is defined
    "//folder/folder2\folder3\file.txt" -> results in "folder3" if position 2 is defined
    "//folder/folder2\folder3\file.txt" -> results in "folder3" if position -2 is defined
    "//folder/folder2\folder3\file.txt" -> results in "folder2" if position -3 is defined

    Parameters

    • path: string

      A string containing some arbitrary path.

    • Default value position: number = -1

      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.

    Returns string

    The element at the specified path position or the last one if no position is defined

Static getPathElementWithoutExt

  • getPathElementWithoutExt(path: string, position?: number, extensionSeparator?: string): 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
    "//folder/folder2\folder3\file.txt" -> results in "folder3" if position = 2. "folder3" has no extension so it does not get modified.

    see

    StringUtils.getPathElement

    Parameters

    • path: string

      A string containing some arbitrary path.

    • Default value position: number = -1

      The index for the element that we want to extract from the path. If not specified, the last one will be returned.

    • Default value extensionSeparator: string = "."

      The character to be used as the extension separator. The most commonly used is '.'

    Returns string

    The element at the specified path position with it's extension removed or the last one if no position is defined

Static getPathExtension

  • getPathExtension(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
    "//folder/folder2\folder3\file.txt" -> results in "folder3" if position = 2. "folder3" has no extension so it does not get modified.

    see

    StringUtils.getPathElement

    Parameters

    • path: string

      A string containing some arbitrary path.

    • Default value position: number = -1

      The index for the element extension that we want to extract from the path. If not specified, the last one will be returned.

    • Default value extensionSeparator: string = "."

      The character to be used as the extension separator. The most commonly used is '.'

    Returns string

    The extension from the element at the specified path position or the extension from the last one if no position is defined

Static getSchemeFromUrl

  • getSchemeFromUrl(url: string): string
  • Given an internet URL, this method extracts only the scheme part. Example: "http://google.com" -> results in "http"

    see

    StringUtils.formatUrl

    Parameters

    • url: string

      A valid internet url

    Returns string

    ('ftp', 'http', ...) if the url is valid or '' if the url is invalid

Static isCamelCase

  • isCamelCase(): void
  • Returns void

Static isEmpty

  • isEmpty(string: string, emptyChars?: string[]): 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"

    Parameters

    • string: string

      The text to check

    • Default value emptyChars: string[] = []

      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', '']

    Returns boolean

    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 isEndingWith

  • isEndingWith(str: string, endingValues?: string[]): boolean
  • Checks if a given string ends with any of the specified values.

    Parameters

    • str: string

      The string to check

    • Default value endingValues: string[] = []

      An array of strings that the input string should end with.

    Returns boolean

    True if the input string ends with any of the specified values, False otherwise.

Static isSnakeCase

  • isSnakeCase(): void
  • Returns void

Static isStartingWith

  • isStartingWith(str: string, startingValues?: string[]): boolean
  • Checks if the given string starts with any of the specified values.

    Parameters

    • str: string

      The string to check

    • Default value startingValues: string[] = []

      An array of strings that the input string should start with.

    Returns boolean

    True if the input string starts with any of the specified values, False otherwise.

Static isString

  • isString(value: any): boolean
  • Tells if the given value is a string or not

    Parameters

    • value: any

      A value to check

    Returns boolean

    true if the given value is a string, false otherwise

Static isUrl

  • isUrl(value: any): boolean
  • Tells if the given string is a valid url or not

    Parameters

    • value: any

      The value to check

    Returns boolean

    False in case the validation fails or true if validation succeeds.

Static limitLen

  • limitLen(string: string, limit?: number, limiterString?: string): string
  • Method that limits the length of a string and optionally appends informative characters like ' ...' to inform that the original string was longer.

    Parameters

    • string: string

      String to limit

    • Default value limit: number = 100

      Max number of characters

    • Default value limiterString: string = " ..."

      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 string

    The specified string but limited in length if necessary. Final result will never exceed the specified limit, also with the limiterString appended.

Static pad

  • pad(string: string, padLength: number, padString?: string, mode?: string): string
  • Pad a string to a certain length with another string

    Parameters

    • string: string

      The string to which we want to fill the empty spaces

    • padLength: number

      The minimum length that we want for the resulting string to have

    • Default value padString: string = "0"

      The character or characters which we want to add to the string to match the target length

    • Default value mode: string = "LEFT"

      LEFT to append the padString to the left of the string, RIGHT to append the padString to the right of the string

    Returns string

    The padded string

Static removeAccents

  • removeAccents(string: string): string

Static removeHtmlCode

  • removeHtmlCode(): void
  • Returns void

Static removeNewLineCharacters

  • removeNewLineCharacters(): void
  • Returns void

Static removeSameConsecutive

  • removeSameConsecutive(string: string, set?: string[]): string
  • Remove all duplicate consecutive fragments from the provided string and leave only one occurence

    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'])

    Parameters

    • string: string

      The string to process

    • Default value set: string[] = []

      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"

    Returns string

    The string with a maximum of one consecutive sequence for all those matching the provided set

Static removeUrls

  • removeUrls(): void
  • Returns void

Static removeWordsLongerThan

  • removeWordsLongerThan(): void
  • Returns void

Static removeWordsShorterThan

  • removeWordsShorterThan(): void
  • Returns void

Static replace

  • replace(string: string, search: string | string[], replacement: string | string[], count?: number): string
  • Replace all occurrences of the search string with the replacement string

    Parameters

    • string: string

      The string or array being searched and replaced on, otherwise known as the haystack.

    • search: string | string[]

      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..)

    • replacement: string | string[]

      The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

    • Default value count: number = -1

      If passed and > 0, this will define the maximum number of replacements to perform

    Returns string

    The string with all the replaced values

Static replaceMulti

  • replaceMulti(object: any, search: string | string[], replacement: string | string[], count?: number): any
  • 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

    Parameters

    • object: any
    • search: string | string[]

      see StringUtils.replace

    • replacement: string | string[]

      see StringUtils.replace

    • Default value count: number = -1

      see StringUtils.replace

    Returns any

    A copy of the provided object or array with all the values replaced on all its strings

Static trim

  • trim(string: string, characters?: string): string
  • Remove whitespaces (or any custom set of characters) from both sides of a string

    example:

    StringUtils.trim("abcXXabc", "abc") outputs "XX"

    Parameters

    • string: string

      A string to process

    • Default value characters: string = ""

      A set of characters that will be trimmed from both string sides. By default, empty space and new line characters are defined : " \n\r"

    Returns string

    The trimmed string

Static trimLeft

  • trimLeft(string: string, characters?: string): string
  • Remove whitespaces (or any custom set of characters) from a string left side

    example:

    StringUtils.trimLeft("abcXXabc", "abc") outputs "XXabc"

    Parameters

    • string: string

      A string to process

    • Default value characters: string = ""

      A set of characters that will be trimmed from string left side. By default, empty space and new line characters are defined : " \n\r"

    Returns string

    The trimmed string

Static trimRight

  • trimRight(string: string, characters?: string): string
  • Remove whitespaces (or any custom set of characters) from a string right side

    example:

    StringUtils.trimRight("abcXXabc", "abc") outputs "abcXX"

    Parameters

    • string: string

      A string to process

    • Default value characters: string = ""

      A set of characters that will be trimmed from string right side. By default, empty space and new line characters are defined : " \n\r"

    Returns string

    The trimmed string

Generated using TypeDoc