string

Classes

goog.string.Parser
An interface for parsing strings into objects.
goog.string.StringBuffer
Utility class to facilitate string concatenation.
goog.string.Stringifier
An interface for serializing objects into strings.

Public Protected Private

Enumerations

goog.string.Unicode :
Common Unicode string characters.
Constants:
NBSP
No description.
Code »

Global Functions

goog.string.buildString(var_args)
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) -> ''
Arguments:
var_args :
*
A list of strings to concatenate. If not a string, it will be casted to one.
Returns:   The concatenation of var_args.
code »
goog.string.canonicalizeNewlines(str)
Replaces Windows and Mac new lines with unix style: \r or \r\n with \n.
Arguments:
str :
The string to in which to canonicalize newlines.
Returns:   str A copy of {@code} with canonicalized newlines.
code »
goog.string.caseInsensitiveCompare(str1str2)
A string comparator that ignores case. -1 = str1 less than str2 0 = str1 equals str2 1 = str1 greater than str2
Arguments:
str1 :
The string to compare.
str2 :
The string to compare str1 to.
Returns:   The comparator result, as described above.
code »
goog.string.caseInsensitiveEndsWith(strsuffix)
Case-insensitive suffix-checker.
Arguments:
str :
The string to check.
suffix :
A string to look for at the end of str.
Returns:   True if str ends with suffix (ignoring case).
code »
goog.string.caseInsensitiveStartsWith(strprefix)
Case-insensitive prefix-checker.
Arguments:
str :
The string to check.
prefix :
A string to look for at the end of str.
Returns:   True if str begins with prefix (ignoring case).
code »
goog.string.collapseBreakingSpaces(str)
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.
Arguments:
str :
A string in which to collapse spaces.
Returns:   Copy of the string with normalized breaking spaces.
code »
goog.string.collapseWhitespace(str)
Converts multiple whitespace chars (spaces, non-breaking-spaces, new lines and tabs) to a single space, and strips leading and trailing whitespace.
Arguments:
str :
Input string.
Returns:   A copy of str with collapsed whitespace.
code »
goog.string.compareElements_(leftright)
Compares elements of a version number.
Arguments:
left :
An element from a version number.
right :
An element from a version number.
Returns:   1 if left is higher. 0 if arguments are equal. -1 if right is higher.
code »
goog.string.compareVersions(version1version2)
Compares two version numbers.
Arguments:
version1 :
Version of first item.
version2 :
Version of second item.
Returns:   1 if version1 is higher. 0 if arguments are equal. -1 if version2 is higher.
code »
goog.string.contains(sss)
Checks whether a string contains a given substring.
Arguments:
s :
The string to test.
ss :
The substring to test for.
Returns:   True if s contains ss.
code »
goog.string.countOf(sss)
Returns the non-overlapping occurrences of ss in s. If either s or ss evalutes to false, then returns zero.
Arguments:
s :
The string to look in.
ss :
The string to look for.
Returns:   Number of occurrences of ss in s.
code »
goog.string.createUniqueString()
Generates and returns a string which is unique in the current document. This is useful, for example, to create unique IDs for DOM elements.
Returns:   A unique id.
code »
goog.string.endsWith(strsuffix)
Fast suffix-checker.
Arguments:
str :
The string to check.
suffix :
A string to look for at the end of str.
Returns:   True if str ends with suffix.
code »
goog.string.escapeChar(c)
Takes a character and returns the escaped string for that character. For example escapeChar(String.fromCharCode(15)) -> "\\x0E".
Arguments:
c :
The character to escape.
Returns:   An escaped string representing c.
code »
goog.string.escapeString(str)
Takes a string and returns the escaped string for that character.
Arguments:
str :
The string to escape.
Returns:   An escaped string representing str.
code »
goog.string.format(formatStringvar_args)
Performs sprintf-like conversion, ie. puts the values in a template. DO NOT use it instead of built-in conversions in simple cases such as 'Cost: %.2f' as it would introduce unneccessary latency oposed to 'Cost: ' + cost.toFixed(2).
Arguments:
formatString :
Template string containing % specifiers.
var_args :
(number | string | undefined)
Values formatString is to be filled with.
Returns:   Formatted string.
code »
goog.string.getRandomString()
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.
Returns:   A random string, e.g. sn1s7vb4gcic.
code »
goog.string.hashCode(str)
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).
Arguments:
str :
A string.
Returns:   Hash value for str, between 0 (inclusive) and 2^32 (exclusive). The empty string returns 0.
code »
goog.string.htmlEscape(stropt_isLikelyToContainHtmlChars)
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.
Arguments:
str :
string to be escaped.
opt_isLikelyToContainHtmlChars :
(boolean | undefined)
Don't perform a check to see if the character needs replacing - use this option if you expect each of the characters to appear often. Leave false if you expect few html characters to occur in your strings, such as if you are escaping HTML.
Returns:   An escaped copy of str.
code »
goog.string.isAlpha(str)
Checks if a string contains all letters.
Arguments:
str :
string to check.
Returns:   True if str consists entirely of letters.
code »
goog.string.isAlphaNumeric(str)
Checks if a string contains only numbers or letters.
Arguments:
str :
string to check.
Returns:   True if str is alphanumeric.
code »
goog.string.isBreakingWhitespace(str)
Checks if a string is all breaking whitespace.
Arguments:
str :
The string to check.
Returns:   Whether the string is all breaking whitespace.
code »
goog.string.isEmpty(str)
Checks if a string is empty or contains only whitespaces.
Arguments:
str :
The string to check.
Returns:   True if str is empty or whitespace only.
code »
goog.string.isEmptySafe(str)
Checks if a string is null, undefined, empty or contains only whitespaces.
Arguments:
str :
*
The string to check.
Returns:   True ifstr is null, undefined, empty, or whitespace only.
code »
goog.string.isNumeric(str)
Checks if a string contains only numbers.
Arguments:
str :
*
string to check. If not a string, it will be casted to one.
Returns:   True if str is numeric.
code »
goog.string.isSpace(ch)
Checks if a character is a space character.
Arguments:
ch :
Character to check.
Returns:   True if {code ch} is a space.
code »
goog.string.isUnicodeChar(ch)
Checks if a character is a valid unicode character.
Arguments:
ch :
Character to check.
Returns:   True if {code ch} is a valid unicode character.
code »
goog.string.makeSafe(obj)
Returns a string representation of the given object, with null and undefined being returned as the empty string.
Arguments:
obj :
*
The object to convert.
Returns:   A string representation of the obj.
code »
goog.string.newLineToBr(stropt_xml)
Converts \n to
s or
s.
Arguments:
str :
The string in which to convert newlines.
opt_xml :
(boolean | undefined)
Whether to use XML compatible tags.
Returns:   A copy of str with converted newlines.
code »
goog.string.normalizeSpaces(str)
Normalizes spaces in a string, replacing all consecutive spaces and tabs with a single space. Replaces non-breaking space with a space.
Arguments:
str :
The string in which to normalize spaces.
Returns:   A copy of str with all consecutive spaces and tabs replaced with a single space.
code »
goog.string.normalizeWhitespace(str)
Normalizes whitespace in a string, replacing all whitespace chars with a space.
Arguments:
str :
The string in which to normalize whitespace.
Returns:   A copy of str with all whitespace normalized.
code »
goog.string.numerateCompare(str1str2)
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.
Arguments:
str1 :
The string to compare in a numerically sensitive way.
str2 :
The string to compare str1 to.
Returns:   less than 0 if str1 < str2, 0 if str1 == str2, greater than 0 if str1 > str2.
code »
goog.string.padNumber(numlengthopt_precision)
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'
Arguments:
num :
The number to pad.
length :
The desired length.
opt_precision :
(number | undefined)
The desired precision.
Returns:   num as a string with the given options.
code »
goog.string.parseInt(value)
Parse a string in decimal or hexidecimal ('0xFFFF') form. To parse a particular radix, please use parseInt(string, radix) directly. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt This is a wrapper for the built-in parseInt function that will only parse numbers as base 10 or base 16. Some JS implementations assume strings starting with "0" are intended to be octal. ES3 allowed but discouraged this behavior. ES5 forbids it. This function emulates the ES5 behavior. For more information, see Mozilla JS Reference: http://goo.gl/8RiFj
Arguments:
value :
(null | number | string | undefined)
The value to be parsed.
Returns:   The number, parsed. If the string failed to parse, this will be NaN.
code »
goog.string.quote(s)
Encloses a string in double quotes and escapes characters so that the string is a valid JS string.
Arguments:
s :
The string to quote.
Returns:   A copy of s surrounded by double quotes.
code »
goog.string.regExpEscape(s)
Escapes characters in the string that are not safe to use in a RegExp.
Arguments:
s :
*
The string to escape. If not a string, it will be casted to one.
Returns:   A RegExp safe, escaped copy of s.
code »
goog.string.remove(sss)
Removes the first occurrence of a substring from a string.
Arguments:
s :
The base string from which to remove.
ss :
The string to remove.
Returns:   A copy of s with ss removed or the full string if nothing is removed.
code »
goog.string.removeAll(sss)
Removes all occurrences of a substring from a string.
Arguments:
s :
The base string from which to remove.
ss :
The string to remove.
Returns:   A copy of s with ss removed or the full string if nothing is removed.
code »
goog.string.removeAt(sindexstringLength)
Removes a substring of a specified length at a specific index in a string.
Arguments:
s :
The base string from which to remove.
index :
The index at which to remove the substring.
stringLength :
The length of the substring to remove.
Returns:   A copy of s with the substring removed or the full string if nothing is removed or the input is invalid.
code »
goog.string.repeat(stringlength)
Repeats a string n times.
Arguments:
string :
The string to repeat.
length :
The number of times to repeat.
Returns:   A string containing length repetitions of string.
code »
goog.string.startsWith(strprefix)
Fast prefix-checker.
Arguments:
str :
The string to check.
prefix :
A string to look for at the start of str.
Returns:   True if str begins with prefix.
code »
goog.string.stripNewlines(str)
Takes a string and replaces newlines with a space. Multiple lines are replaced with a single space.
Arguments:
str :
The string from which to strip newlines.
Returns:   A copy of str stripped of newlines.
code »
goog.string.stripQuotes(strquoteChars)
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'
Arguments:
str :
The string to strip.
quoteChars :
The quote characters to strip.
Returns:   A copy of str without the quotes.
code »
goog.string.subs(strvar_args)
Does simple python-style string substitution. subs("foo%s hot%s", "bar", "dog") becomes "foobar hotdog".
Arguments:
str :
The string containing the pattern.
var_args :
*
The items to substitute into the pattern.
Returns:   A copy of str in which each occurrence of %s has been replaced an argument from var_args.
code »
goog.string.toCamelCase(str)
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.
Arguments:
str :
The string in selector-case form.
Returns:   The string in camelCase form.
code »
goog.string.toMap(s)
(Object | null)
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.
Arguments:
s :
The string to build the map from.
Returns: 
(Object | null)
  The map of characters used.
code »
goog.string.toNumber(str)
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)
Arguments:
str :
The string to convert.
Returns:   The number the supplied string represents, or NaN.
code »
goog.string.toSelectorCase(str)
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.
Arguments:
str :
The string in camelCase form.
Returns:   The string in selector-case form.
code »
goog.string.toTitleCase(stropt_delimiters)
Converts a string into TitleCase. First character of the string is always capitalized in addition to the first letter of every subsequent word. Words are delimited by one or more whitespaces by default. Custom delimiters can optionally be specified to replace the default, which doesn't preserve whitespace delimiters and instead must be explicitly included if needed. Default delimiter => " ": goog.string.toTitleCase('oneTwoThree') => 'OneTwoThree' goog.string.toTitleCase('one two three') => 'One Two Three' goog.string.toTitleCase(' one two ') => ' One Two ' goog.string.toTitleCase('one_two_three') => 'One_two_three' goog.string.toTitleCase('one-two-three') => 'One-two-three' Custom delimiter => "_-.": goog.string.toTitleCase('oneTwoThree', '_-.') => 'OneTwoThree' goog.string.toTitleCase('one two three', '_-.') => 'One two three' goog.string.toTitleCase(' one two ', '_-.') => ' one two ' goog.string.toTitleCase('one_two_three', '_-.') => 'One_Two_Three' goog.string.toTitleCase('one-two-three', '_-.') => 'One-Two-Three' goog.string.toTitleCase('one...two...three', '_-.') => 'One...Two...Three' goog.string.toTitleCase('one. two. three', '_-.') => 'One. two. three' goog.string.toTitleCase('one-two.three', '_-.') => 'One-Two.Three'
Arguments:
str :
String value in camelCase form.
opt_delimiters :
(string | undefined)
Custom delimiter character set used to distinguish words in the string value. Each character represents a single delimiter. When provided, default whitespace delimiter is overridden and must be explicitly included if needed.
Returns:   String value in TitleCase form.
code »
goog.string.trim(str)
Trims white spaces to the left and right of a string.
Arguments:
str :
The string to trim.
Returns:   A trimmed copy of str.
code »
goog.string.trimLeft(str)
Trims whitespaces at the left end of a string.
Arguments:
str :
The string to left trim.
Returns:   A trimmed copy of str.
code »
goog.string.trimRight(str)
Trims whitespaces at the right end of a string.
Arguments:
str :
The string to right trim.
Returns:   A trimmed copy of str.
code »
goog.string.truncate(strcharsopt_protectEscapedCharacters)
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...'.
Arguments:
str :
The string to truncate.
chars :
Max number of characters.
opt_protectEscapedCharacters :
(boolean | undefined)
Whether to protect escaped characters from being cut off in the middle.
Returns:   The truncated str string.
code »
goog.string.truncateMiddle(strcharsopt_protectEscapedCharactersopt_trailingChars)
Truncate a string in the middle, adding "..." if necessary, and favoring the beginning of the string.
Arguments:
str :
The string to truncate the middle of.
chars :
Max number of characters.
opt_protectEscapedCharacters :
(boolean | undefined)
Whether to protect escaped characters from being cutoff in the middle.
opt_trailingChars :
(number | undefined)
Optional number of trailing characters to leave at the end of the string, instead of truncating as close to the middle as possible.
Returns:   A truncated copy of str.
code »
goog.string.unescapeEntities(str)
Unescapes an HTML string.
Arguments:
str :
The string to unescape.
Returns:   An unescaped copy of str.
code »
goog.string.unescapeEntitiesUsingDom_(str)
Unescapes an HTML string using a DOM to resolve non-XML, non-numeric entities. This function is XSS-safe and whitespace-preserving.
Arguments:
str :
The string to unescape.
Returns:   The unescaped str string.
code »
goog.string.unescapePureXmlEntities_(str)
Unescapes XML entities.
Arguments:
str :
The string to unescape.
Returns:   An unescaped copy of str.
code »
goog.string.urlDecode(str)
URL-decodes the string. We need to specially handle '+'s because the javascript library doesn't convert them to spaces.
Arguments:
str :
The string to url decode.
Returns:   The decoded str.
code »
goog.string.urlEncode(str)
URL-encodes a string
Arguments:
str :
*
The string to url-encode.
Returns:   An encoded copy of str that is safe for urls. Note that &#39;#&#39;, &#39;:&#39;, and other characters used to delimit portions of URLs *will* be encoded.
code »
goog.string.whitespaceEscape(stropt_xml)
Do escaping of whitespace to preserve spatial formatting. We use character entity #160 to make it safer for xml.
Arguments:
str :
The string in which to escape whitespace.
opt_xml :
(boolean | undefined)
Whether to use XML compatible tags.
Returns:   An escaped copy of str.
code »

Global Properties

goog.string.HASHCODE_MAX_ :
Maximum value of #goog.string.hashCode, exclusive. 2^32.
Code »
goog.string.HTML_ENTITY_PATTERN_ :
Regular expression that matches an HTML entity. See also HTML5: Tokenization / Tokenizing character references.
Code »
goog.string.allRe_ :
(RegExp | null)
Regular expression that matches any character that needs to be escaped.
Code »
goog.string.amperRe_ :
(RegExp | null)
Regular expression that matches an ampersand, for use in escaping.
Code »
goog.string.gtRe_ :
(RegExp | null)
Regular expression that matches a greater than sign, for use in escaping.
Code »
goog.string.jsEscapeCache_ :
(Object | null)
Character mappings used internally for goog.string.escapeChar.
Code »
goog.string.ltRe_ :
(RegExp | null)
Regular expression that matches a less than sign, for use in escaping.
Code »
goog.string.numerateCompareRegExp_ :
(RegExp | null)
Regular expression used for splitting a string into substrings of fractional numbers, integers, and non-numeric characters.
Code »
goog.string.quotRe_ :
(RegExp | null)
Regular expression that matches a double quote, for use in escaping.
Code »
goog.string.specialEscapeChars_ :
(Object | null)
Special chars that need to be escaped for goog.string.quote.
Code »
goog.string.uniqueStringCounter_ :
The most recent unique ID. |0 is equivalent to Math.floor in this case.
Code »

Package string

Package Reference