}
*/
goog.string.jsEscapeCache_ = {
'\'': '\\\''
};
/**
* Encloses a string in double quotes and escapes characters so that the
* string is a valid JS string.
* @param {string} s The string to quote.
* @return {string} A copy of {@code s} surrounded by double quotes.
*/
goog.string.quote = function(s) {
s = String(s);
if (s.quote) {
return s.quote();
} else {
var sb = ['"'];
for (var i = 0; i < s.length; i++) {
var ch = s.charAt(i);
var cc = ch.charCodeAt(0);
sb[i + 1] = goog.string.specialEscapeChars_[ch] ||
((cc > 31 && cc < 127) ? ch : goog.string.escapeChar(ch));
}
sb.push('"');
return sb.join('');
}
};
/**
* Takes a string and returns the escaped string for that character.
* @param {string} str The string to escape.
* @return {string} An escaped string representing {@code str}.
*/
goog.string.escapeString = function(str) {
var sb = [];
for (var i = 0; i < str.length; i++) {
sb[i] = goog.string.escapeChar(str.charAt(i));
}
return sb.join('');
};
/**
* Takes a character and returns the escaped string for that character. For
* example escapeChar(String.fromCharCode(15)) -> "\\x0E".
* @param {string} c The character to escape.
* @return {string} An escaped string representing {@code c}.
*/
goog.string.escapeChar = function(c) {
if (c in goog.string.jsEscapeCache_) {
return goog.string.jsEscapeCache_[c];
}
if (c in goog.string.specialEscapeChars_) {
return goog.string.jsEscapeCache_[c] = goog.string.specialEscapeChars_[c];
}
var rv = c;
var cc = c.charCodeAt(0);
if (cc > 31 && cc < 127) {
rv = c;
} else {
// tab is 9 but handled above
if (cc < 256) {
rv = '\\x';
if (cc < 16 || cc > 256) {
rv += '0';
}
} else {
rv = '\\u';
if (cc < 4096) { // \u1000
rv += '0';
}
}
rv += cc.toString(16).toUpperCase();
}
return goog.string.jsEscapeCache_[c] = rv;
};
/**
* Determines whether a string contains a substring.
* @param {string} str The string to search.
* @param {string} subString The substring to search for.
* @return {boolean} Whether {@code str} contains {@code subString}.
*/
goog.string.contains = function(str, subString) {
return str.indexOf(subString) != -1;
};
/**
* Determines whether a string contains a substring, ignoring case.
* @param {string} str The string to search.
* @param {string} subString The substring to search for.
* @return {boolean} Whether {@code str} contains {@code subString}.
*/
goog.string.caseInsensitiveContains = function(str, subString) {
return goog.string.contains(str.toLowerCase(), subString.toLowerCase());
};
/**
* Returns the non-overlapping occurrences of ss in s.
* If either s or ss evalutes to false, then returns zero.
* @param {string} s The string to look in.
* @param {string} ss The string to look for.
* @return {number} Number of occurrences of ss in s.
*/
goog.string.countOf = function(s, ss) {
return s && ss ? s.split(ss).length - 1 : 0;
};
/**
* Removes a substring of a specified length at a specific
* index in a string.
* @param {string} s The base string from which to remove.
* @param {number} index The index at which to remove the substring.
* @param {number} stringLength The length of the substring to remove.
* @return {string} A copy of {@code s} with the substring removed or the full
* string if nothing is removed or the input is invalid.
*/
goog.string.removeAt = function(s, index, stringLength) {
var resultStr = s;
// If the index is greater or equal to 0 then remove substring
if (index >= 0 && index < s.length && stringLength > 0) {
resultStr = s.substr(0, index) +
s.substr(index + stringLength, s.length - index - stringLength);
}
return resultStr;
};
/**
* Removes the first occurrence of a substring from a string.
* @param {string} s The base string from which to remove.
* @param {string} ss The string to remove.
* @return {string} A copy of {@code s} with {@code ss} removed or the full
* string if nothing is removed.
*/
goog.string.remove = function(s, ss) {
var re = new RegExp(goog.string.regExpEscape(ss), '');
return s.replace(re, '');
};
/**
* Removes all occurrences of a substring from a string.
* @param {string} s The base string from which to remove.
* @param {string} ss The string to remove.
* @return {string} A copy of {@code s} with {@code ss} removed or the full
* string if nothing is removed.
*/
goog.string.removeAll = function(s, ss) {
var re = new RegExp(goog.string.regExpEscape(ss), 'g');
return s.replace(re, '');
};
/**
* Escapes characters in the string that are not safe to use in a RegExp.
* @param {*} s The string to escape. If not a string, it will be casted
* to one.
* @return {string} A RegExp safe, escaped copy of {@code s}.
*/
goog.string.regExpEscape = function(s) {
return String(s).replace(/([-()\[\]{}+?*.$\^|,:#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'
*
* @param {number} num The number to pad.
* @param {number} length The desired length.
* @param {number=} opt_precision The desired precision.
* @return {string} {@code num} as a string with the given options.
*/
goog.string.padNumber = function(num, length, opt_precision) {
var s = goog.isDef(opt_precision) ? num.toFixed(opt_precision) : String(num);
var index = s.indexOf('.');
if (index == -1) {
index = s.length;
}
return goog.string.repeat('0', Math.max(0, length - index)) + s;
};
/**
* Returns a string representation of the given object, with
* null and undefined being returned as the empty string.
*
* @param {*} obj The object to convert.
* @return {string} A string representation of the {@code obj}.
*/
goog.string.makeSafe = function(obj) {
return obj == null ? '' : String(obj);
};
/**
* 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) -> ''
*
* @param {...*} var_args A list of strings to concatenate. If not a string,
* it will be casted to one.
* @return {string} The concatenation of {@code var_args}.
*/
goog.string.buildString = function(var_args) {
return Array.prototype.join.call(arguments, '');
};
/**
* 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.
*
* @return {string} A random string, e.g. sn1s7vb4gcic.
*/
goog.string.getRandomString = function() {
var x = 2147483648;
return Math.floor(Math.random() * x).toString(36) +
Math.abs(Math.floor(Math.random() * x) ^ goog.now()).toString(36);
};
/**
* Compares two version numbers.
*
* @param {string|number} version1 Version of first item.
* @param {string|number} version2 Version of second item.
*
* @return {number} 1 if {@code version1} is higher.
* 0 if arguments are equal.
* -1 if {@code version2} is higher.
*/
goog.string.compareVersions = function(version1, version2) {
var order = 0;
// Trim leading and trailing whitespace and split the versions into
// subversions.
var v1Subs = goog.string.trim(String(version1)).split('.');
var v2Subs = goog.string.trim(String(version2)).split('.');
var subCount = Math.max(v1Subs.length, v2Subs.length);
// Iterate over the subversions, as long as they appear to be equivalent.
for (var subIdx = 0; order == 0 && subIdx < subCount; subIdx++) {
var v1Sub = v1Subs[subIdx] || '';
var v2Sub = v2Subs[subIdx] || '';
// Split the subversions into pairs of numbers and qualifiers (like 'b').
// Two different RegExp objects are needed because they are both using
// the 'g' flag.
var v1CompParser = new RegExp('(\\d*)(\\D*)', 'g');
var v2CompParser = new RegExp('(\\d*)(\\D*)', 'g');
do {
var v1Comp = v1CompParser.exec(v1Sub) || ['', '', ''];
var v2Comp = v2CompParser.exec(v2Sub) || ['', '', ''];
// Break if there are no more matches.
if (v1Comp[0].length == 0 && v2Comp[0].length == 0) {
break;
}
// Parse the numeric part of the subversion. A missing number is
// equivalent to 0.
var v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10);
var v2CompNum = v2Comp[1].length == 0 ? 0 : parseInt(v2Comp[1], 10);
// Compare the subversion components. The number has the highest
// precedence. Next, if the numbers are equal, a subversion without any
// qualifier is always higher than a subversion with any qualifier. Next,
// the qualifiers are compared as strings.
order = goog.string.compareElements_(v1CompNum, v2CompNum) ||
goog.string.compareElements_(v1Comp[2].length == 0,
v2Comp[2].length == 0) ||
goog.string.compareElements_(v1Comp[2], v2Comp[2]);
// Stop as soon as an inequality is discovered.
} while (order == 0);
}
return order;
};
/**
* Compares elements of a version number.
*
* @param {string|number|boolean} left An element from a version number.
* @param {string|number|boolean} right An element from a version number.
*
* @return {number} 1 if {@code left} is higher.
* 0 if arguments are equal.
* -1 if {@code right} is higher.
* @private
*/
goog.string.compareElements_ = function(left, right) {
if (left < right) {
return -1;
} else if (left > right) {
return 1;
}
return 0;
};
/**
* Maximum value of #goog.string.hashCode, exclusive. 2^32.
* @type {number}
* @private
*/
goog.string.HASHCODE_MAX_ = 0x100000000;
/**
* 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).
* @param {string} str A string.
* @return {number} Hash value for {@code str}, between 0 (inclusive) and 2^32
* (exclusive). The empty string returns 0.
*/
goog.string.hashCode = function(str) {
var result = 0;
for (var i = 0; i < str.length; ++i) {
result = 31 * result + str.charCodeAt(i);
// Normalize to 4 byte range, 0 ... 2^32.
result %= goog.string.HASHCODE_MAX_;
}
return result;
};
/**
* The most recent unique ID. |0 is equivalent to Math.floor in this case.
* @type {number}
* @private
*/
goog.string.uniqueStringCounter_ = Math.random() * 0x80000000 | 0;
/**
* Generates and returns a string which is unique in the current document.
* This is useful, for example, to create unique IDs for DOM elements.
* @return {string} A unique id.
*/
goog.string.createUniqueString = function() {
return 'goog_' + goog.string.uniqueStringCounter_++;
};
/**
* Converts the supplied string to a number, which may be Infinity 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)
*
* @param {string} str The string to convert.
* @return {number} The number the supplied string represents, or NaN.
*/
goog.string.toNumber = function(str) {
var num = Number(str);
if (num == 0 && goog.string.isEmptyOrWhitespace(str)) {
return NaN;
}
return num;
};
/**
* Returns whether the given string is lower camel case (e.g. "isFooBar").
*
* Note that this assumes the string is entirely letters.
* @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms
*
* @param {string} str String to test.
* @return {boolean} Whether the string is lower camel case.
*/
goog.string.isLowerCamelCase = function(str) {
return /^[a-z]+([A-Z][a-z]*)*$/.test(str);
};
/**
* Returns whether the given string is upper camel case (e.g. "FooBarBaz").
*
* Note that this assumes the string is entirely letters.
* @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms
*
* @param {string} str String to test.
* @return {boolean} Whether the string is upper camel case.
*/
goog.string.isUpperCamelCase = function(str) {
return /^([A-Z][a-z]*)+$/.test(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.
* @param {string} str The string in selector-case form.
* @return {string} The string in camelCase form.
*/
goog.string.toCamelCase = function(str) {
return String(str).replace(/\-([a-z])/g, function(all, match) {
return match.toUpperCase();
});
};
/**
* 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.
* @param {string} str The string in camelCase form.
* @return {string} The string in selector-case form.
*/
goog.string.toSelectorCase = function(str) {
return String(str).replace(/([A-Z])/g, '-$1').toLowerCase();
};
/**
* 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'
*
* @param {string} str String value in camelCase form.
* @param {string=} opt_delimiters 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.
* @return {string} String value in TitleCase form.
*/
goog.string.toTitleCase = function(str, opt_delimiters) {
var delimiters = goog.isString(opt_delimiters) ?
goog.string.regExpEscape(opt_delimiters) : '\\s';
// For IE8, we need to prevent using an empty character set. Otherwise,
// incorrect matching will occur.
delimiters = delimiters ? '|[' + delimiters + ']+' : '';
var regexp = new RegExp('(^' + delimiters + ')([a-z])', 'g');
return str.replace(regexp, function(all, p1, p2) {
return p1 + p2.toUpperCase();
});
};
/**
* Capitalizes a string, i.e. converts the first letter to uppercase
* and all other letters to lowercase, e.g.:
*
* goog.string.capitalize('one') => 'One'
* goog.string.capitalize('ONE') => 'One'
* goog.string.capitalize('one two') => 'One two'
*
* Note that this function does not trim initial whitespace.
*
* @param {string} str String value to capitalize.
* @return {string} String value with first letter in uppercase.
*/
goog.string.capitalize = function(str) {
return String(str.charAt(0)).toUpperCase() +
String(str.substr(1)).toLowerCase();
};
/**
* 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
*
* @param {string|number|null|undefined} value The value to be parsed.
* @return {number} The number, parsed. If the string failed to parse, this
* will be NaN.
*/
goog.string.parseInt = function(value) {
// Force finite numbers to strings.
if (isFinite(value)) {
value = String(value);
}
if (goog.isString(value)) {
// If the string starts with '0x' or '-0x', parse as hex.
return /^\s*-?0x/i.test(value) ?
parseInt(value, 16) : parseInt(value, 10);
}
return NaN;
};
/**
* Splits a string on a separator a limited number of times.
*
* This implementation is more similar to Python or Java, where the limit
* parameter specifies the maximum number of splits rather than truncating
* the number of results.
*
* See http://docs.python.org/2/library/stdtypes.html#str.split
* See JavaDoc: http://goo.gl/F2AsY
* See Mozilla reference: http://goo.gl/dZdZs
*
* @param {string} str String to split.
* @param {string} separator The separator.
* @param {number} limit The limit to the number of splits. The resulting array
* will have a maximum length of limit+1. Negative numbers are the same
* as zero.
* @return {!Array} The string, split.
*/
goog.string.splitLimit = function(str, separator, limit) {
var parts = str.split(separator);
var returnVal = [];
// Only continue doing this while we haven't hit the limit and we have
// parts left.
while (limit > 0 && parts.length) {
returnVal.push(parts.shift());
limit--;
}
// If there are remaining parts, append them to the end.
if (parts.length) {
returnVal.push(parts.join(separator));
}
return returnVal;
};
/**
* Computes the Levenshtein edit distance between two strings.
* @param {string} a
* @param {string} b
* @return {number} The edit distance between the two strings.
*/
goog.string.editDistance = function(a, b) {
var v0 = [];
var v1 = [];
if (a == b) {
return 0;
}
if (!a.length || !b.length) {
return Math.max(a.length, b.length);
}
for (var i = 0; i < b.length + 1; i++) {
v0[i] = i;
}
for (var i = 0; i < a.length; i++) {
v1[0] = i + 1;
for (var j = 0; j < b.length; j++) {
var cost = a[i] != b[j];
// Cost for the substring is the minimum of adding one character, removing
// one character, or a swap.
v1[j + 1] = Math.min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost);
}
for (var j = 0; j < v0.length; j++) {
v0[j] = v1[j];
}
}
return v1[b.length];
};