RingoJS

Module ringo/utils/strings

Adds useful methods to the JavaScript String type.

Functions


Sorter (field, order)

Factory to create functions for sorting objects in an array.

Example

const arr = [{ name: "Foo", age: 10 }, {name: "Bar", age: 20 }];

// returns [ { name: 'Bar', age: 20 }, { name: 'Foo', age: 10 } ]
const x = arr.sort(new Sorter("name", 1));

// returns [ { name: 'Foo', age: 10 }, { name: 'Bar', age: 20 } ]
x.sort(new Sorter("name", -1));

Parameters

String field

name of the field each object is compared with

Number order

(ascending or descending)

Returns

Function

ready for use in Array.prototype.sort


b16decode (str, encoding)

Decodes a Base16 encoded string to a string or byte array.

Example

strings.b16decode("666F6F"); // --> "foo"
strings.b16decode("666F6F", "raw"); // --> [ByteArray 3]

Parameters

String str

the Base16 encoded string

String encoding

the encoding to use for the return value. Defaults to 'utf8'. Use 'raw' to get a ByteArray instead of a string.

Returns

String|ByteArray

the decoded string or ByteArray


b16encode (str, encoding)

Encode a string or binary to a Base16 encoded string.

Example

strings.b16encode("foo"); // --> "666F6F"

Parameters

String|Binary str

a string or binary

String encoding

optional encoding to use if first argument is a string. Defaults to 'utf8'.

Returns

String

the Base16 encoded string


b64decode (string, encoding)

Decodes a Base64 encoded string to a string or byte array.

Example

strings.b64decode("Zm9vYg=="); // --> "foob"
strings.b64decode("Zm9vYg==", "raw"); // --> [ByteArray 4]

Parameters

String string

the Base64 encoded string

String encoding

the encoding to use for the return value. Defaults to 'utf8'. Use 'raw' to get a ByteArray instead of a string.

Returns

String|ByteArray

the decoded string or ByteArray


b64encode (string, encoding)

Encode a string or binary to a Base64 encoded string.

Example

strings.b64encode("foob"); // --> "Zm9vYg=="

Parameters

String|Binary string

a string or binary

String encoding

optional encoding to use if first argument is a string. Defaults to 'utf8'.

Returns

String

the Base64 encoded string


capitalize (string, limit)

Transforms the first n characters of a string to uppercase.

Example

strings.capitalize("example text"); // "Example text"
strings.capitalize("example text", 7); // EXAMPLE text

Parameters

String string

the string to capitalize

Number limit

amount of characters to transform

Returns

String

the resulting string


compose (one)

Create a string from a bunch of substrings.

Example

strings.compose("foo", "bar", "baz"); // --> "foobarbaz"

Parameters

String one

or more strings as arguments

Returns

String

the resulting string


contains (string, substring, fromIndex)

Returns true if string contains substring.

Example

strings.contains("foobar", "oba"); // --> true
strings.contains("foobar", "baz"); // --> false
strings.contains("foobar", "oo", 1); // --> true
strings.contains("foobar", "oo", 2); // --> false

Parameters

String string

the string to search in

String substring

the string to search for

Number fromIndex

optional index to start searching

Returns

Boolean

true if substring is contained in this string


count (string, pattern)

Returns the amount of occurrences of one string in another.

Example

strings.count("foobarfoo", "foo"); // --> 2

Parameters

String string
String pattern

Returns

Number

occurrences


digest (string, algorithm)

Calculates a message digest of a string. If no argument is passed, the MD5 algorithm is used. All algorithms supported by java.security.MessageDigest can be requested. Every Java platform must provide an implementation of MD5, SHA-1, and SHA-256. All known popular Java platform implementations will also provide SHA-224, SHA-384, and SHA-512.

Example

// "C3499C2729730A7F807EFB8676A92DCB6F8A3F8F"
strings.digest("example", "sha-1");

Parameters

String string

the string to digest

String algorithm

the name of the algorithm to use

Returns

String

base16-encoded message digest of the string


endsWith (string, substring)

Returns true if string ends with the given substring.

Example

strings.endsWith("foobar", "bar"); // --> true
strings.endsWith("foobar", "foo"); // --> false

Parameters

String string

the string to search in

String substring

pattern to search for

Returns

Boolean

true in case it matches the end of the string, false otherwise


entitize (string)

Translates all characters of a string into HTML entities. Entities are encoded in decimal form of Unicode code points.

Example

strings.entitize("@foo"); // --> "@foo"

Parameters

String string

the string

Returns

String

translated result


escapeHtml (string)

Escape the string to make it safe for use within an HTML document. Unsafe characters are &, ", ', `, <, and >.

Example

// returns "&lt;a href=&#39;foo&#39;&gt;bar&lt;/a&gt;"
strings.escapeHtml("<a href='foo'>bar</a>");

Parameters

String string

the string to escape

Returns

String

the escaped string


escapeRegExp (str)

Accepts a string; returns the string with regex metacharacters escaped. the returned string can safely be used within a regex to match a literal string. escaped characters are [, ], {, }, (, ), -, *, +, ?, ., , ^, $, |, #, [comma], and whitespace.

Example

// returns "/\.\*foo\+bar/"
strings.escapeRegExp("/.*foo+bar/");

Parameters

String str

the string to escape

Returns

String

the escaped string


format (format)

A simple string formatter. If the first argument is a format string containing a number of curly bracket pairs {} as placeholders, the same number of following arguments will be used to replace the curly bracket pairs in the format string. If the first argument is not a string or does not contain any curly brackets, the arguments are simply concatenated to a string and returned.

Example

// "My age is 10!"
strings.format("My {} is {}!", "age", 10);

// My age is 10! 20 30
strings.format("My {} is {}!", "age", 10, 20, 30);

Parameters

String format

string, followed by a variable number of values

Returns

String

the formatted string


getCommonPrefix (str1, str2)

Get the longest common segment that two strings have in common, starting at the beginning of the string.

Example

strings.getCommonPrefix("foobarbaz", "foobazbar"); // --> "fooba"
strings.getCommonPrefix("foobarbaz", "bazbarfoo"); // --> ""

Parameters

String str1

a string

String str2

another string

Returns

String

the longest common segment


group (string, interval, str, ignoreWhiteSpace)

Inserts a string every number of characters.

Example

// returns "fobaro fobaro fobaro"
strings.group("foo foo foo", 2, "bar");

// returns "fobaro barfobaro barfobarobar"
strings.group("foo foo foo", 2, "bar", true);

Parameters

String string
Number interval

number of characters after which insertion should take place, defaults to 20

String str

string to be inserted

Boolean ignoreWhiteSpace

optional, definitely insert at each interval position

Returns

String

resulting string


isAlpha (string)

Returns true if the string contains only characters a-z and A-Z.

Example

strings.isAlpha("foo"); // --> true
strings.isAlpha("foo123"); // --> false

Parameters

String string

the string

Returns

Boolean

true in case string is alpha, false otherwise


isAlphanumeric (string)

Returns true if the string contains only a-z, A-Z and 0-9 (case insensitive).

Example

strings.isAlphanumeric("foobar123"); // --> true
strings.isAlphanumeric("foo@example"); // --> false

Parameters

String string

the string

Returns

Boolean

true in case string is alpha, false otherwise


isDate (string, format, locale, timezone, lenient)

Returns true if the string is matching a date format. By default the parser matches the pattern against the string with lenient parsing: Even if the input is not strictly in the form of the pattern, but can be parsed with heuristics, then the parse succeeds. For details on the format pattern, see java.text.SimpleDateFormat . If no format is provided, the check uses a patter matching RFC 3339 (timestamps on the internet).

Example

// true
strings.isDate("2016");
strings.isDate("01-01-2016", "MM-dd-yyyy");

// true, since lenient parsing
strings.isDate("20-40-2016", "MM-dd-yyyy");

// false, since strict parsing with lenient=false
strings.isDate("20-40-2016", "MM-dd-yyyy", "en", "UTC", false);

Parameters

String string
String format

(optional) date format pattern

String|java.util.Locale locale

(optional) the locale as java Locale object or lowercase two-letter ISO-639 code (e.g. "en")

String|java.util.TimeZone timezone

(optional) the timezone as java TimeZone object or an abbreviation such as "PST", a full name such as "America/Los_Angeles", or a custom ID such as "GMT-8:00". If the id is not provided, the default timezone is used. If the timezone id is provided but cannot be understood, the "GMT" timezone is used.

Boolean lenient

(optional) disables lenient parsing if set to false.

Returns

Boolean

true if valid date string, false otherwise


isDateFormat (string)

Checks if a date format pattern is correct and a valid string to create a new java.text.SimpleDateFormat from it.

Example

strings.isDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z"); // --> true
strings.isDateFormat(""); // --> true
strings.isDateFormat("PPPP"); // --> false

Parameters

String string

the string

Returns

Boolean

true if the pattern is correct, false otherwise


isEmail (string)

Returns true if the string looks like an e-mail. It does not perform an extended validation or any mailbox checks.

Example

strings.isEmail("rhino@ringojs.org"); // --> true
strings.isEmail("rhino@ringojs"); // --> false

Parameters

String string

Returns

Boolean

true if the string is an e-mail address


isFileName (string)

Checks if the string passed contains any characters that are forbidden in image- or filenames. Allowed characters are: [a-z][A-Z][0-9]-_. and blank space.

Example

// true
strings.isFileName("foo123.bar");
strings.isFileName("foo bar baz");
strings.isFileName("foo-bar.baz");
strings.isFileName("..baz");

// false
strings.isFileName("../foo");
strings.isFileName("foo/bar/baz");
strings.isFileName("foo-bar+baz");

Parameters

String string

the string

Returns

Boolean

isFloat (string)

Returns true if the string is a floating point literal.

Example

strings.isFloat("0.0"); // --> true
strings.isFloat("10.01234"); // --> true
strings.isFloat("-0.0"); // --> true
strings.isFloat("+10.0"); // --> true

strings.isFloat("foo"); // --> false
strings.isFloat("0"); // --> false

Parameters

String string

Returns

Boolean

true if floating point literal, false otherwise


isHexColor (string)

Checks a string for a valid color value in hexadecimal format. It may also contain # as first character.

Example

// true
strings.isHexColor("#f0f1f4");
strings.isHexColor("f0f1f4");
strings.isHexColor("#caffee");

// false
strings.isHexColor("#000");
strings.isHexColor("000");
strings.isHexColor("#matcha");
strings.isHexColor("#tea");

Parameters

String string

the string

Returns

Boolean

false, if string length (without #) > 6 or < 6 or contains any character which is not a valid hex value


isInt (string)

Returns true if the string is an integer literal.

Example

strings.isInt("0"); // --> true
strings.isInt("123"); // --> true
strings.isInt("+123"); // --> true
strings.isInt("-123"); // --> true

strings.isInt("0123"); // --> false
strings.isInt("bar"); // --> false

Parameters

String string

Returns

Boolean

true if integer literal, false otherwise


isLowerCase (string)

Returns true if the string is lowercase.

Example

strings.isLowerCase("foo"); // --> true
strings.isLowerCase("Foo"); // --> false

Parameters

String string

Returns

Boolean

true if lowercase, false otherwise


isNumeric (string)

Returns true if the string contains only 0-9.

Example

strings.isNumeric("12345"); // --> true
strings.isNumeric("00012345"); // --> true
strings.isAlpha("foo123"); // --> false

Parameters

String string

the string

Returns

Boolean

true in case string is numeric, false otherwise


isUpperCase (string)

Returns true if the string is uppercase.

Example

strings.isUpperCase("FOO"); // --> true
strings.isUpperCase("FOo"); // --> false

Parameters

String string

Returns

Boolean

true if uppercase, false otherwise


isUrl (string)

Checks if the string is a valid URL. Only HTTP, HTTPS and FTP are allowed protocols. TLDs are mandatory so hostnames like localhost fail. 1.0.0.0 - 223.255.255.255 is the valid IP range. Though, IP addresses with a broadcast class are considered as invalid.

Example

// true
strings.isUrl("http://example.com");
strings.isUrl("https://example.com");
strings.isUrl("ftp://foo@bar.com");
strings.isUrl("http://example.com/q?exp=a|b");

// false
strings.isUrl("http://localhost");
strings.isUrl("ftp://foo");
strings.isUrl("//example.com");
strings.isUrl("http://10.1.1.255");

Parameters

String string

the string

Returns

Boolean

true if the string is a valid URL


join (str1, str2, str3)

Append one string onto another and add some "glue" if none of the strings is empty or null.

Example

strings.join("foo", "bar"); // "foobar"
strings.join("foo", "bar", "-"); // "foo-bar"
strings.join("foo", "",  "-"); // "foo"

Parameters

String str1

the first string

String str2

the string to be appended onto the first one

String str3

the "glue" to be inserted between both strings

Returns

String

the resulting string


pad (string, fill, length, mode)

Fills a string with another string up to a desired length.

Example

// "hellowo"
strings.pad("hello", "world", 7);

// "wohello"
strings.pad("hello", "world", 7, -1);

// "whellow"
strings.pad("hello", "world", 7, 0);

// "helloworldworldworld"
strings.pad("hello", "world", 20);

// "worldwohelloworldwor"
strings.pad("hello", "world", 20, 0);

Parameters

String string

the string

String fill

the filling string

Number length

the desired length of the resulting string

Number mode

the direction which the string will be padded in: a negative number means left, 0 means both, a positive number means right

Returns

String

the resulting string


random (len, mode)

Creates a random string (numbers and chars).

Example

strings.random(10); // --> "wcn1v5h0tg"
strings.random(10, 1); // --> "bqpfj36tn4"
strings.random(10, 2); // --> 5492950742

Parameters

Number len

length of key

Number mode

determines which letters to use. null or 0 = all letters; 1 = skip 0, 1, l and o which can easily be mixed with numbers; 2 = use numbers only

Returns

String

random string


repeat (string, num)

Repeats a string passed as argument multiple times.

Example

strings.repeat("foo", 3); // --> "foofoofoo"

Parameters

String string

the string

Number num

amount of repetitions

Returns

String

resulting string


startsWith (string, substring)

Returns true if string starts with the given substring.

Example

strings.startsWith("foobar", "foo"); // --> true
strings.startsWith("foobar", "bar"); // --> false

Parameters

String string

the string to search in

String substring

pattern to search for

Returns

Boolean

true in case it matches the beginning of the string, false otherwise


titleize (string, amount)

Transforms the first n characters of each word in a string to uppercase.

Example

strings.titleize("the bar is foo"); // --> "The Bar Is Foo"
strings.titleize("the bar is foo", 2); // --> "THe BAr IS FOo"
strings.titleize("the bar is foo", 3); // --> "THE BAR IS FOO"

Parameters

String string

the string

Number amount

optional number of characters to transform

Returns

String

the resulting string


toAlphanumeric (string)

Cleans a string by throwing away all non-alphanumeric characters.

Example

// returns "dogdogecom"
strings.toAlphanumeric("dog@doge.com");

Parameters

String string

the string

Returns

String

cleaned string


toCamelCase (string)

Transforms string from space, dash, or underscore notation to camel-case.

Example

strings.toCamelCase("TheDogJumps"); // "TheDogJumps"
strings.toCamelCase("the-dog_jumps"); // "theDogJumps"
strings.toCamelCase("FOObarBaz"); // "FoobarBaz"

Parameters

String string

a string

Returns

String

the resulting string


toDashes (string)

Transforms string from camel-case to dash notation.

Example

strings.toDashes("FooBarBaz"); // "-foo-bar-baz"
strings.toDashes("fooBARBaz"); // "foo-b-a-r-baz"
strings.toDashes("foo-Bar-Baz"); // "foo--bar--baz"

Parameters

String string

a string

Returns

String

the resulting string


toDate (string, format, timezone)

Parse a timestamp into a Date object.

Example

// Thu Dec 24 2015 00:00:00 GMT+0100 (MEZ)
strings.toDate("24-12-2015", "dd-MM-yyyy");

// Thu Dec 24 2015 09:00:00 GMT+0100 (MEZ)
const tz = java.util.TimeZone.getTimeZone("America/Los_Angeles");
strings.toDate("24-12-2015", "dd-MM-yyyy", tz);

Parameters

String string

the string

String format

date format to be applied

java.util.TimeZone timezone

Java TimeZone Object (optional)

Returns

Date

the resulting date


toFileName (string)

Cleans the string passed as argument from any characters that are forbidden or shouldn't be used in filenames.

Example

// returns "..foobarbaz"
strings.toFileName("../foo/bar+baz");

Parameters

String string

the string

Returns

String

the sanitized string


toHexColor (string)

Deprecated!
This function is unreliable and a remnant from Helma's String module.

Converts a string into a hexadecimal color representation (e.g. "ffcc33"). Also knows how to convert a color string like "rgb (255, 204, 51)".

Example

strings.toHexColor("rgb(255, 204, 51)"); // --> ffcc33
strings.toHexColor("rgb (255, 204, 51)"); // --> ffcc33
strings.toHexColor("rgba(255, 204, 51)"); // --> ffcc33

Parameters

String string

the string

Returns

String

the resulting hex color (w/o "#")


toUnderscores (string)

Transforms string from camel-case to underscore notation.

Example

strings.toUnderscores("FooBarBaz"); // "_foo_bar_baz"
strings.toUnderscores("fooBARBaz"); // "foo_b_a_r_baz"
strings.toUnderscores("foo_Bar_Baz"); // "foo__bar__baz"
strings.toUnderscores("foo-Bar-Baz"); // foo-_bar-_baz

Parameters

String string

a string

Returns

String

the resulting string


y64decode (string, encoding)

Decodes a Y64 encoded string to a string or byte array.

Example

strings.y64decode("Zm9vYg--"); // --> "foob"
strings.y64decode("Zm9vYg--", "raw"); // --> [ByteArray 4]

Parameters

String string

the Y64 encoded string

String encoding

the encoding to use for the return value. Defaults to 'utf8'. Use 'raw' to get a ByteArray instead of a string.

Returns

String|ByteArray

the decoded string or ByteArray


y64encode (string, encoding)

Encode a string or binary to a Y64 encoded string. Y64 is an URL-safe Base64 encoding and prevents any URL escaping. It replaces the plus (+), slash (/) and equals (=) with dot (.), underscore (_) and dash (-).

Example

strings.y64encode("foob"); // --> "Zm9vYg--"

Parameters

String|Binary string

a string or binary

String encoding

optional encoding to use if first argument is a string. Defaults to 'utf8'.

Returns

String

the Y64 encoded string