Home

# Library goog.string

Function Summary

`buildString(<Any Type> var_args) ⇒ string`

Concatenates string expressions. This is useful since some browsers are very inefficient when it comes to using plus to concat strings. Be careful when using null and undefined here since these will not be included in the result. If you need to represent these be sure to cast the argument to a String first. For example:

    buildString('a', 'b', 'c', 'd') -> 'abcd'
    buildString(null, undefined) -> ''

| `canonicalizeNewlines(string str) ⇒ string` Replaces Windows and Mac new lines with unix style: \r or \r\n with \n.
| `caseInsensitiveCompare(string str1, string str2) ⇒ number` A string comparator that ignores case. -1 = str1 less than str2 0 = str1 equals str2 1 = str1 greater than str2
| `caseInsensitiveEndsWith(string str, string suffix) ⇒ boolean` Case-insensitive suffix-checker.
| `caseInsensitiveStartsWith(string str, string prefix) ⇒ boolean` Case-insensitive prefix-checker.
| `collapseBreakingSpaces(string str) ⇒ string` Removes the breaking spaces from the left and right of the string and collapses the sequences of breaking spaces in the middle into single spaces. The original and the result strings render the same way in HTML.
| `collapseWhitespace(string str) ⇒ string` Converts multiple whitespace chars (spaces, non-breaking-spaces, new lines and tabs) to a single space, and strips leading and trailing whitespace.
| `compareElements_((boolean|number|string) left, (boolean|number|string) right) ⇒ number` Compares elements of a version number.
| `compareVersions((number|string) version1, (number|string) version2) ⇒ number` Compares two version numbers.
| `contains(string s, string ss) ⇒ boolean` Checks whether a string contains a given character.
| `countOf(string s, string ss) ⇒ number` Returns the non-overlapping occurrences of ss in s. If either s or ss evalutes to false, then returns zero.
| `createUniqueString() ⇒ string` Generates and returns a string which is unique in the current document. This is useful, for example, to create unique IDs for DOM elements.
| `endsWith(string str, string suffix) ⇒ boolean` Fast suffix-checker.
| `escapeChar(string c) ⇒ string` Takes a character and returns the escaped string for that character. For example escapeChar(String.fromCharCode(15)) -> "\\x0E".
| `escapeString(string str) ⇒ string` Takes a string and returns the escaped string for that character.
| `getRandomString() ⇒ string` Returns a string with at least 64-bits of randomness. Doesn't trust Javascript's random function entirely. Uses a combination of random and current timestamp, and then encodes the string in base-36 to make it shorter.
| `hashCode(string str) ⇒ number` String hash function similar to java.lang.String.hashCode(). The hash code for a string is computed as s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], where s[i] is the ith character of the string and n is the length of the string. We mod the result to make it between 0 (inclusive) and 2^32 (exclusive).

`htmlEscape(string str, boolean= opt_isLikelyToContainHtmlChars) ⇒ string`

Escape double quote '"' characters in addition to '&', '<', and '>' so that a string can be included in an HTML tag attribute value within double quotes. It should be noted that > doesn't need to be escaped for the HTML or XML to be valid, but it has been decided to escape it for consistency with other implementations. NOTE(user): HtmlEscape is often called during the generation of large blocks of HTML. Using statics for the regular expressions and strings is an optimization that can more than half the amount of time IE spends in this function for large apps, since strings and regexes both contribute to GC allocations. Testing for the presence of a character before escaping increases the number of function calls, but actually provides a speed increase for the average case -- since the average case often doesn't require the escaping of all 4 characters and indexOf() is much cheaper than replace(). The worst case does suffer slightly from the additional calls, therefore the opt_isLikelyToContainHtmlChars option has been included for situations where all 4 HTML entities are very likely to be present and need escaping. Some benchmarks (times tended to fluctuate +-0.05ms): FireFox IE6 (no chars / average (mix of cases) / all 4 chars) no checks 0.13 / 0.22 / 0.22 0.23 / 0.53 / 0.80 indexOf 0.08 / 0.17 / 0.26 0.22 / 0.54 / 0.84 indexOf + re test 0.07 / 0.17 / 0.28 0.19 / 0.50 / 0.85 An additional advantage of checking if replace actually needs to be called is a reduction in the number of object allocations, so as the size of the application grows the difference between the various methods would increase.

| `isAlpha(string str) ⇒ boolean` Checks if a string contains all letters.
| `isAlphaNumeric(string str) ⇒ boolean` Checks if a string contains only numbers or letters.
| `isBreakingWhitespace(string str) ⇒ boolean` Checks if a string is all breaking whitespace.
| `isEmpty(string str) ⇒ boolean` Checks if a string is empty or contains only whitespaces.
| `isEmptySafe(<Any Type> str) ⇒ boolean` Checks if a string is null, empty or contains only whitespaces.
| `isNumeric(<Any Type> str) ⇒ boolean` Checks if a string contains only numbers.
| `isSpace(string ch) ⇒ boolean` Checks if a character is a space character.
| `isUnicodeChar(string ch) ⇒ boolean` Checks if a character is a valid unicode character.
| `makeSafe(<Any Type> obj) ⇒ string` Returns a string representation of the given object, with null and undefined being returned as the empty string.
| `newLineToBr(string str, boolean= opt_xml) ⇒ string` Converts \n to s or s.
| `normalizeSpaces(string str) ⇒ string` Normalizes spaces in a string, replacing all consecutive spaces and tabs with a single space. Replaces non-breaking space with a space.
| `normalizeWhitespace(string str) ⇒ string` Normalizes whitespace in a string, replacing all whitespace chars with a space.

`numerateCompare(string str1, string str2) ⇒ number`

String comparison function that handles numbers in a way humans might expect. Using this function, the string "File 2.jpg" sorts before "File 10.jpg". The comparison is mostly case-insensitive, though strings that are identical except for case are sorted with the upper-case strings before lower-case. This comparison function is significantly slower (about 500x) than either the default or the case-insensitive compare. It should not be used in time-critical code, but should be fast enough to sort several hundred short strings (like filenames) with a reasonable delay.

`padNumber(number num, number length, number= opt_precision) ⇒ string`

Pads number to given length and optionally rounds it to a given precision. For example:

    padNumber(1.25, 2, 3) -> '01.250'
    padNumber(1.25, 2) -> '01.25'
    padNumber(1.25, 2, 1) -> '01.3'
    padNumber(1.25, 0) -> '1.25'

| `quote(string s) ⇒ string` Encloses a string in double quotes and escapes characters so that the string is a valid JS string.
| `regExpEscape(<Any Type> s) ⇒ string` Escapes characters in the string that are not safe to use in a RegExp.
| `remove(string s, string ss) ⇒ string` Removes the first occurrence of a substring from a string.
| `removeAll(string s, string ss) ⇒ string` Removes all occurrences of a substring from a string.
| `removeAt(string s, number index, number stringLength) ⇒ string` Removes a substring of a specified length at a specific index in a string.
| `repeat(string string, number length) ⇒ string` Repeats a string n times.
| `startsWith(string str, string prefix) ⇒ boolean` Fast prefix-checker.
| `stripNewlines(string str) ⇒ string` Takes a string and replaces newlines with a space. Multiple lines are replaced with a single space.

`stripQuotes(string str, string quoteChars) ⇒ string`

Strip quote characters around a string. The second argument is a string of characters to treat as quotes. This can be a single character or a string of multiple character and in that case each of those are treated as possible quote characters. For example:

    goog.string.stripQuotes('"abc"', '"`') --> 'abc'
    goog.string.stripQuotes('`abc`', '"`') --> 'abc'

| `subs(string str, <Any Type> var_args) ⇒ string` Does simple python-style string substitution. subs("foo%s hot%s", "bar", "dog") becomes "foobar hotdog".
| `toCamelCase(string str) ⇒ string` Converts a string from selector-case to camelCase (e.g. from "multi-part-string" to "multiPartString"), useful for converting CSS selectors and HTML dataset keys to their equivalent JS properties.
| `toMap(string s) ⇒ ?Object` Takes a string and creates a map (Object) in which the keys are the characters in the string. The value for the key is set to true. You can then use goog.object.map or goog.array.map to change the values.
| `toNumber(string str) ⇒ number` Converts the supplied string to a number, which may be Ininity or NaN. This function strips whitespace: (toNumber(' 123') === 123) This function accepts scientific notation: (toNumber('1e1') === 10) This is better than Javascript's built-in conversions because, sadly: (Number(' ') === 0) and (parseFloat('123a') === 123)
| `toSelectorCase(string str) ⇒ string` Converts a string from camelCase to selector-case (e.g. from "multiPartString" to "multi-part-string"), useful for converting JS style and dataset properties to equivalent CSS selectors and HTML keys.
| `trim(string str) ⇒ string` Trims white spaces to the left and right of a string.
| `trimLeft(string str) ⇒ string` Trims whitespaces at the left end of a string.
| `trimRight(string str) ⇒ string` Trims whitespaces at the right end of a string.
| `truncate(string str, number chars, boolean= opt_protectEscapedCharacters) ⇒ string` Truncates a string to a certain length and adds '...' if necessary. The length also accounts for the ellipsis, so a maximum length of 10 and a string 'Hello World!' produces 'Hello W...'.
| `truncateMiddle(string str, number chars, boolean= opt_protectEscapedCharacters, number= opt_trailingChars) ⇒ string` Truncate a string in the middle, adding "..." if necessary, and favoring the beginning of the string.
| `unescapeEntities(string str) ⇒ string` Unescapes an HTML string.
| `unescapeEntitiesUsingDom_(string str) ⇒ string` Unescapes an HTML string using a DOM to resolve non-XML, non-numeric entities. This function is XSS-safe and whitespace-preserving.
| `unescapePureXmlEntities_(string str) ⇒ string` Unescapes XML entities.
| `urlDecode(string str) ⇒ string` URL-decodes the string. We need to specially handle '+'s because the javascript library doesn't convert them to spaces.
| `urlEncode(<Any Type> str) ⇒ string` URL-encodes a string
| `whitespaceEscape(string str, boolean= opt_xml) ⇒ string` Do escaping of whitespace to preserve spatial formatting. We use character entity #160 to make it safer for xml.