| 1 |
// Copyright 2006 The Closure Library Authors. All Rights Reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS-IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
/** |
| 16 |
* @fileoverview Utilities for string manipulation. |
| 17 |
* @author [email protected] (Erik Arvidsson) |
| 18 |
*/ |
| 19 |
|
| 20 |
|
| 21 |
/** |
| 22 |
* Namespace for string utilities |
| 23 |
*/ |
| 24 |
goog.provide('goog.string'); |
| 25 |
goog.provide('goog.string.Unicode'); |
| 26 |
|
| 27 |
|
| 28 |
/** |
| 29 |
* @define {boolean} Enables HTML escaping of lowercase letter "e" which helps |
| 30 |
* with detection of double-escaping as this letter is frequently used. |
| 31 |
*/ |
| 32 |
goog.define('goog.string.DETECT_DOUBLE_ESCAPING', false); |
| 33 |
|
| 34 |
|
| 35 |
/** |
| 36 |
* @define {boolean} Whether to force non-dom html unescaping. |
| 37 |
*/ |
| 38 |
goog.define('goog.string.FORCE_NON_DOM_HTML_UNESCAPING', false); |
| 39 |
|
| 40 |
|
| 41 |
/** |
| 42 |
* Common Unicode string characters. |
| 43 |
* @enum {string} |
| 44 |
*/ |
| 45 |
goog.string.Unicode = { |
| 46 |
NBSP: '\xa0' |
| 47 |
}; |
| 48 |
|
| 49 |
|
| 50 |
/** |
| 51 |
* Fast prefix-checker. |
| 52 |
* @param {string} str The string to check. |
| 53 |
* @param {string} prefix A string to look for at the start of {@code str}. |
| 54 |
* @return {boolean} True if {@code str} begins with {@code prefix}. |
| 55 |
*/ |
| 56 |
goog.string.startsWith = function(str, prefix) { |
| 57 |
return str.lastIndexOf(prefix, 0) == 0; |
| 58 |
}; |
| 59 |
|
| 60 |
|
| 61 |
/** |
| 62 |
* Fast suffix-checker. |
| 63 |
* @param {string} str The string to check. |
| 64 |
* @param {string} suffix A string to look for at the end of {@code str}. |
| 65 |
* @return {boolean} True if {@code str} ends with {@code suffix}. |
| 66 |
*/ |
| 67 |
goog.string.endsWith = function(str, suffix) { |
| 68 |
var l = str.length - suffix.length; |
| 69 |
return l >= 0 && str.indexOf(suffix, l) == l; |
| 70 |
}; |
| 71 |
|
| 72 |
|
| 73 |
/** |
| 74 |
* Case-insensitive prefix-checker. |
| 75 |
* @param {string} str The string to check. |
| 76 |
* @param {string} prefix A string to look for at the end of {@code str}. |
| 77 |
* @return {boolean} True if {@code str} begins with {@code prefix} (ignoring |
| 78 |
* case). |
| 79 |
*/ |
| 80 |
goog.string.caseInsensitiveStartsWith = function(str, prefix) { |
| 81 |
return goog.string.caseInsensitiveCompare( |
| 82 |
prefix, str.substr(0, prefix.length)) == 0; |
| 83 |
}; |
| 84 |
|
| 85 |
|
| 86 |
/** |
| 87 |
* Case-insensitive suffix-checker. |
| 88 |
* @param {string} str The string to check. |
| 89 |
* @param {string} suffix A string to look for at the end of {@code str}. |
| 90 |
* @return {boolean} True if {@code str} ends with {@code suffix} (ignoring |
| 91 |
* case). |
| 92 |
*/ |
| 93 |
goog.string.caseInsensitiveEndsWith = function(str, suffix) { |
| 94 |
return ( |
| 95 |
goog.string.caseInsensitiveCompare( |
| 96 |
suffix, str.substr(str.length - suffix.length, suffix.length)) == 0); |
| 97 |
}; |
| 98 |
|
| 99 |
|
| 100 |
/** |
| 101 |
* Case-insensitive equality checker. |
| 102 |
* @param {string} str1 First string to check. |
| 103 |
* @param {string} str2 Second string to check. |
| 104 |
* @return {boolean} True if {@code str1} and {@code str2} are the same string, |
| 105 |
* ignoring case. |
| 106 |
*/ |
| 107 |
goog.string.caseInsensitiveEquals = function(str1, str2) { |
| 108 |
return str1.toLowerCase() == str2.toLowerCase(); |
| 109 |
}; |
| 110 |
|
| 111 |
|
| 112 |
/** |
| 113 |
* Does simple python-style string substitution. |
| 114 |
* subs("foo%s hot%s", "bar", "dog") becomes "foobar hotdog". |
| 115 |
* @param {string} str The string containing the pattern. |
| 116 |
* @param {...*} var_args The items to substitute into the pattern. |
| 117 |
* @return {string} A copy of {@code str} in which each occurrence of |
| 118 |
* {@code %s} has been replaced an argument from {@code var_args}. |
| 119 |
*/ |
| 120 |
goog.string.subs = function(str, var_args) { |
| 121 |
var splitParts = str.split('%s'); |
| 122 |
var returnString = ''; |
| 123 |
|
| 124 |
var subsArguments = Array.prototype.slice.call(arguments, 1); |
| 125 |
while (subsArguments.length && |
| 126 |
// Replace up to the last split part. We are inserting in the |
| 127 |
// positions between split parts. |
| 128 |
splitParts.length > 1) { |
| 129 |
returnString += splitParts.shift() + subsArguments.shift(); |
| 130 |
} |
| 131 |
|
| 132 |
return returnString + splitParts.join('%s'); // Join unused '%s' |
| 133 |
}; |
| 134 |
|
| 135 |
|
| 136 |
/** |
| 137 |
* Converts multiple whitespace chars (spaces, non-breaking-spaces, new lines |
| 138 |
* and tabs) to a single space, and strips leading and trailing whitespace. |
| 139 |
* @param {string} str Input string. |
| 140 |
* @return {string} A copy of {@code str} with collapsed whitespace. |
| 141 |
*/ |
| 142 |
goog.string.collapseWhitespace = function(str) { |
| 143 |
// Since IE doesn't include non-breaking-space (0xa0) in their \s character |
| 144 |
// class (as required by section 7.2 of the ECMAScript spec), we explicitly |
| 145 |
// include it in the regexp to enforce consistent cross-browser behavior. |
| 146 |
return str.replace(/[\s\xa0]+/g, ' ').replace(/^\s+|\s+$/g, ''); |
| 147 |
}; |
| 148 |
|
| 149 |
|
| 150 |
/** |
| 151 |
* Checks if a string is empty or contains only whitespaces. |
| 152 |
* @param {string} str The string to check. |
| 153 |
* @return {boolean} Whether {@code str} is empty or whitespace only. |
| 154 |
*/ |
| 155 |
goog.string.isEmptyOrWhitespace = function(str) { |
| 156 |
// testing length == 0 first is actually slower in all browsers (about the |
| 157 |
// same in Opera). |
| 158 |
// Since IE doesn't include non-breaking-space (0xa0) in their \s character |
| 159 |
// class (as required by section 7.2 of the ECMAScript spec), we explicitly |
| 160 |
// include it in the regexp to enforce consistent cross-browser behavior. |
| 161 |
return /^[\s\xa0]*$/.test(str); |
| 162 |
}; |
| 163 |
|
| 164 |
|
| 165 |
/** |
| 166 |
* Checks if a string is empty. |
| 167 |
* @param {string} str The string to check. |
| 168 |
* @return {boolean} Whether {@code str} is empty. |
| 169 |
*/ |
| 170 |
goog.string.isEmptyString = function(str) { |
| 171 |
return str.length == 0; |
| 172 |
}; |
| 173 |
|
| 174 |
|
| 175 |
/** |
| 176 |
* Checks if a string is empty or contains only whitespaces. |
| 177 |
* |
| 178 |
* @param {string} str The string to check. |
| 179 |
* @return {boolean} Whether {@code str} is empty or whitespace only. |
| 180 |
* @deprecated Use goog.string.isEmptyOrWhitespace instead. |
| 181 |
*/ |
| 182 |
goog.string.isEmpty = goog.string.isEmptyOrWhitespace; |
| 183 |
|
| 184 |
|
| 185 |
/** |
| 186 |
* Checks if a string is null, undefined, empty or contains only whitespaces. |
| 187 |
* @param {*} str The string to check. |
| 188 |
* @return {boolean} Whether {@code str} is null, undefined, empty, or |
| 189 |
* whitespace only. |
| 190 |
* @deprecated Use goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str)) |
| 191 |
* instead. |
| 192 |
*/ |
| 193 |
goog.string.isEmptyOrWhitespaceSafe = function(str) { |
| 194 |
return goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str)); |
| 195 |
}; |
| 196 |
|
| 197 |
|
| 198 |
/** |
| 199 |
* Checks if a string is null, undefined, empty or contains only whitespaces. |
| 200 |
* |
| 201 |
* @param {*} str The string to check. |
| 202 |
* @return {boolean} Whether {@code str} is null, undefined, empty, or |
| 203 |
* whitespace only. |
| 204 |
* @deprecated Use goog.string.isEmptyOrWhitespace instead. |
| 205 |
*/ |
| 206 |
goog.string.isEmptySafe = goog.string.isEmptyOrWhitespaceSafe; |
| 207 |
|
| 208 |
|
| 209 |
/** |
| 210 |
* Checks if a string is all breaking whitespace. |
| 211 |
* @param {string} str The string to check. |
| 212 |
* @return {boolean} Whether the string is all breaking whitespace. |
| 213 |
*/ |
| 214 |
goog.string.isBreakingWhitespace = function(str) { |
| 215 |
return !/[^\t\n\r ]/.test(str); |
| 216 |
}; |
| 217 |
|
| 218 |
|
| 219 |
/** |
| 220 |
* Checks if a string contains all letters. |
| 221 |
* @param {string} str string to check. |
| 222 |
* @return {boolean} True if {@code str} consists entirely of letters. |
| 223 |
*/ |
| 224 |
goog.string.isAlpha = function(str) { |
| 225 |
return !/[^a-zA-Z]/.test(str); |
| 226 |
}; |
| 227 |
|
| 228 |
|
| 229 |
/** |
| 230 |
* Checks if a string contains only numbers. |
| 231 |
* @param {*} str string to check. If not a string, it will be |
| 232 |
* casted to one. |
| 233 |
* @return {boolean} True if {@code str} is numeric. |
| 234 |
*/ |
| 235 |
goog.string.isNumeric = function(str) { |
| 236 |
return !/[^0-9]/.test(str); |
| 237 |
}; |
| 238 |
|
| 239 |
|
| 240 |
/** |
| 241 |
* Checks if a string contains only numbers or letters. |
| 242 |
* @param {string} str string to check. |
| 243 |
* @return {boolean} True if {@code str} is alphanumeric. |
| 244 |
*/ |
| 245 |
goog.string.isAlphaNumeric = function(str) { |
| 246 |
return !/[^a-zA-Z0-9]/.test(str); |
| 247 |
}; |
| 248 |
|
| 249 |
|
| 250 |
/** |
| 251 |
* Checks if a character is a space character. |
| 252 |
* @param {string} ch Character to check. |
| 253 |
* @return {boolean} True if {@code ch} is a space. |
| 254 |
*/ |
| 255 |
goog.string.isSpace = function(ch) { |
| 256 |
return ch == ' '; |
| 257 |
}; |
| 258 |
|
| 259 |
|
| 260 |
/** |
| 261 |
* Checks if a character is a valid unicode character. |
| 262 |
* @param {string} ch Character to check. |
| 263 |
* @return {boolean} True if {@code ch} is a valid unicode character. |
| 264 |
*/ |
| 265 |
goog.string.isUnicodeChar = function(ch) { |
| 266 |
return ch.length == 1 && ch >= ' ' && ch <= '~' || |
| 267 |
ch >= '\u0080' && ch <= '\uFFFD'; |
| 268 |
}; |
| 269 |
|
| 270 |
|
| 271 |
/** |
| 272 |
* Takes a string and replaces newlines with a space. Multiple lines are |
| 273 |
* replaced with a single space. |
| 274 |
* @param {string} str The string from which to strip newlines. |
| 275 |
* @return {string} A copy of {@code str} stripped of newlines. |
| 276 |
*/ |
| 277 |
goog.string.stripNewlines = function(str) { |
| 278 |
return str.replace(/(\r\n|\r|\n)+/g, ' '); |
| 279 |
}; |
| 280 |
|
| 281 |
|
| 282 |
/** |
| 283 |
* Replaces Windows and Mac new lines with unix style: \r or \r\n with \n. |
| 284 |
* @param {string} str The string to in which to canonicalize newlines. |
| 285 |
* @return {string} {@code str} A copy of {@code} with canonicalized newlines. |
| 286 |
*/ |
| 287 |
goog.string.canonicalizeNewlines = function(str) { |
| 288 |
return str.replace(/(\r\n|\r|\n)/g, '\n'); |
| 289 |
}; |
| 290 |
|
| 291 |
|
| 292 |
/** |
| 293 |
* Normalizes whitespace in a string, replacing all whitespace chars with |
| 294 |
* a space. |
| 295 |
* @param {string} str The string in which to normalize whitespace. |
| 296 |
* @return {string} A copy of {@code str} with all whitespace normalized. |
| 297 |
*/ |
| 298 |
goog.string.normalizeWhitespace = function(str) { |
| 299 |
return str.replace(/\xa0|\s/g, ' '); |
| 300 |
}; |
| 301 |
|
| 302 |
|
| 303 |
/** |
| 304 |
* Normalizes spaces in a string, replacing all consecutive spaces and tabs |
| 305 |
* with a single space. Replaces non-breaking space with a space. |
| 306 |
* @param {string} str The string in which to normalize spaces. |
| 307 |
* @return {string} A copy of {@code str} with all consecutive spaces and tabs |
| 308 |
* replaced with a single space. |
| 309 |
*/ |
| 310 |
goog.string.normalizeSpaces = function(str) { |
| 311 |
return str.replace(/\xa0|[ \t]+/g, ' '); |
| 312 |
}; |
| 313 |
|
| 314 |
|
| 315 |
/** |
| 316 |
* Removes the breaking spaces from the left and right of the string and |
| 317 |
* collapses the sequences of breaking spaces in the middle into single spaces. |
| 318 |
* The original and the result strings render the same way in HTML. |
| 319 |
* @param {string} str A string in which to collapse spaces. |
| 320 |
* @return {string} Copy of the string with normalized breaking spaces. |
| 321 |
*/ |
| 322 |
goog.string.collapseBreakingSpaces = function(str) { |
| 323 |
return str.replace(/[\t\r\n ]+/g, ' ') |
| 324 |
.replace(/^[\t\r\n ]+|[\t\r\n ]+$/g, ''); |
| 325 |
}; |
| 326 |
|
| 327 |
|
| 328 |
/** |
| 329 |
* Trims white spaces to the left and right of a string. |
| 330 |
* @param {string} str The string to trim. |
| 331 |
* @return {string} A trimmed copy of {@code str}. |
| 332 |
*/ |
| 333 |
goog.string.trim = |
| 334 |
(goog.TRUSTED_SITE && String.prototype.trim) ? function(str) { |
| 335 |
return str.trim(); |
| 336 |
} : function(str) { |
| 337 |
// Since IE doesn't include non-breaking-space (0xa0) in their \s |
| 338 |
// character class (as required by section 7.2 of the ECMAScript spec), |
| 339 |
// we explicitly include it in the regexp to enforce consistent |
| 340 |
// cross-browser behavior. |
| 341 |
// NOTE: We don't use String#replace because it might have side effects |
| 342 |
// causing this function to not compile to 0 bytes. |
| 343 |
return /^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(str)[1]; |
| 344 |
}; |
| 345 |
|
| 346 |
|
| 347 |
/** |
| 348 |
* Trims whitespaces at the left end of a string. |
| 349 |
* @param {string} str The string to left trim. |
| 350 |
* @return {string} A trimmed copy of {@code str}. |
| 351 |
*/ |
| 352 |
goog.string.trimLeft = function(str) { |
| 353 |
// Since IE doesn't include non-breaking-space (0xa0) in their \s character |
| 354 |
// class (as required by section 7.2 of the ECMAScript spec), we explicitly |
| 355 |
// include it in the regexp to enforce consistent cross-browser behavior. |
| 356 |
return str.replace(/^[\s\xa0]+/, ''); |
| 357 |
}; |
| 358 |
|
| 359 |
|
| 360 |
/** |
| 361 |
* Trims whitespaces at the right end of a string. |
| 362 |
* @param {string} str The string to right trim. |
| 363 |
* @return {string} A trimmed copy of {@code str}. |
| 364 |
*/ |
| 365 |
goog.string.trimRight = function(str) { |
| 366 |
// Since IE doesn't include non-breaking-space (0xa0) in their \s character |
| 367 |
// class (as required by section 7.2 of the ECMAScript spec), we explicitly |
| 368 |
// include it in the regexp to enforce consistent cross-browser behavior. |
| 369 |
return str.replace(/[\s\xa0]+$/, ''); |
| 370 |
}; |
| 371 |
|
| 372 |
|
| 373 |
/** |
| 374 |
* A string comparator that ignores case. |
| 375 |
* -1 = str1 less than str2 |
| 376 |
* 0 = str1 equals str2 |
| 377 |
* 1 = str1 greater than str2 |
| 378 |
* |
| 379 |
* @param {string} str1 The string to compare. |
| 380 |
* @param {string} str2 The string to compare {@code str1} to. |
| 381 |
* @return {number} The comparator result, as described above. |
| 382 |
*/ |
| 383 |
goog.string.caseInsensitiveCompare = function(str1, str2) { |
| 384 |
var test1 = String(str1).toLowerCase(); |
| 385 |
var test2 = String(str2).toLowerCase(); |
| 386 |
|
| 387 |
if (test1 < test2) { |
| 388 |
return -1; |
| 389 |
} else if (test1 == test2) { |
| 390 |
return 0; |
| 391 |
} else { |
| 392 |
return 1; |
| 393 |
} |
| 394 |
}; |
| 395 |
|
| 396 |
|
| 397 |
/** |
| 398 |
* Compares two strings interpreting their numeric substrings as numbers. |
| 399 |
* |
| 400 |
* @param {string} str1 First string. |
| 401 |
* @param {string} str2 Second string. |
| 402 |
* @param {!RegExp} tokenizerRegExp Splits a string into substrings of |
| 403 |
* non-negative integers, non-numeric characters and optionally fractional |
| 404 |
* numbers starting with a decimal point. |
| 405 |
* @return {number} Negative if str1 < str2, 0 is str1 == str2, positive if |
| 406 |
* str1 > str2. |
| 407 |
* @private |
| 408 |
*/ |
| 409 |
goog.string.numberAwareCompare_ = function(str1, str2, tokenizerRegExp) { |
| 410 |
if (str1 == str2) { |
| 411 |
return 0; |
| 412 |
} |
| 413 |
if (!str1) { |
| 414 |
return -1; |
| 415 |
} |
| 416 |
if (!str2) { |
| 417 |
return 1; |
| 418 |
} |
| 419 |
|
| 420 |
// Using match to split the entire string ahead of time turns out to be faster |
| 421 |
// for most inputs than using RegExp.exec or iterating over each character. |
| 422 |
var tokens1 = str1.toLowerCase().match(tokenizerRegExp); |
| 423 |
var tokens2 = str2.toLowerCase().match(tokenizerRegExp); |
| 424 |
|
| 425 |
var count = Math.min(tokens1.length, tokens2.length); |
| 426 |
|
| 427 |
for (var i = 0; i < count; i++) { |
| 428 |
var a = tokens1[i]; |
| 429 |
var b = tokens2[i]; |
| 430 |
|
| 431 |
// Compare pairs of tokens, returning if one token sorts before the other. |
| 432 |
if (a != b) { |
| 433 |
// Only if both tokens are integers is a special comparison required. |
| 434 |
// Decimal numbers are sorted as strings (e.g., '.09' < '.1'). |
| 435 |
var num1 = parseInt(a, 10); |
| 436 |
if (!isNaN(num1)) { |
| 437 |
var num2 = parseInt(b, 10); |
| 438 |
if (!isNaN(num2) && num1 - num2) { |
| 439 |
return num1 - num2; |
| 440 |
} |
| 441 |
} |
| 442 |
return a < b ? -1 : 1; |
| 443 |
} |
| 444 |
} |
| 445 |
|
| 446 |
// If one string is a substring of the other, the shorter string sorts first. |
| 447 |
if (tokens1.length != tokens2.length) { |
| 448 |
return tokens1.length - tokens2.length; |
| 449 |
} |
| 450 |
|
| 451 |
// The two strings must be equivalent except for case (perfect equality is |
| 452 |
// tested at the head of the function.) Revert to default ASCII string |
| 453 |
// comparison to stabilize the sort. |
| 454 |
return str1 < str2 ? -1 : 1; |
| 455 |
}; |
| 456 |
|
| 457 |
|
| 458 |
/** |
| 459 |
* String comparison function that handles non-negative integer numbers in a |
| 460 |
* way humans might expect. Using this function, the string 'File 2.jpg' sorts |
| 461 |
* before 'File 10.jpg', and 'Version 1.9' before 'Version 1.10'. The comparison |
| 462 |
* is mostly case-insensitive, though strings that are identical except for case |
| 463 |
* are sorted with the upper-case strings before lower-case. |
| 464 |
* |
| 465 |
* This comparison function is up to 50x slower than either the default or the |
| 466 |
* case-insensitive compare. It should not be used in time-critical code, but |
| 467 |
* should be fast enough to sort several hundred short strings (like filenames) |
| 468 |
* with a reasonable delay. |
| 469 |
* |
| 470 |
* @param {string} str1 The string to compare in a numerically sensitive way. |
| 471 |
* @param {string} str2 The string to compare {@code str1} to. |
| 472 |
* @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than |
| 473 |
* 0 if str1 > str2. |
| 474 |
*/ |
| 475 |
goog.string.intAwareCompare = function(str1, str2) { |
| 476 |
return goog.string.numberAwareCompare_(str1, str2, /\d+|\D+/g); |
| 477 |
}; |
| 478 |
|
| 479 |
|
| 480 |
/** |
| 481 |
* String comparison function that handles non-negative integer and fractional |
| 482 |
* numbers in a way humans might expect. Using this function, the string |
| 483 |
* 'File 2.jpg' sorts before 'File 10.jpg', and '3.14' before '3.2'. Equivalent |
| 484 |
* to {@link goog.string.intAwareCompare} apart from the way how it interprets |
| 485 |
* dots. |
| 486 |
* |
| 487 |
* @param {string} str1 The string to compare in a numerically sensitive way. |
| 488 |
* @param {string} str2 The string to compare {@code str1} to. |
| 489 |
* @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than |
| 490 |
* 0 if str1 > str2. |
| 491 |
*/ |
| 492 |
goog.string.floatAwareCompare = function(str1, str2) { |
| 493 |
return goog.string.numberAwareCompare_(str1, str2, /\d+|\.\d+|\D+/g); |
| 494 |
}; |
| 495 |
|
| 496 |
|
| 497 |
/** |
| 498 |
* Alias for {@link goog.string.floatAwareCompare}. |
| 499 |
* |
| 500 |
* @param {string} str1 |
| 501 |
* @param {string} str2 |
| 502 |
* @return {number} |
| 503 |
*/ |
| 504 |
goog.string.numerateCompare = goog.string.floatAwareCompare; |
| 505 |
|
| 506 |
|
| 507 |
/** |
| 508 |
* URL-encodes a string |
| 509 |
* @param {*} str The string to url-encode. |
| 510 |
* @return {string} An encoded copy of {@code str} that is safe for urls. |
| 511 |
* Note that '#', ':', and other characters used to delimit portions |
| 512 |
* of URLs *will* be encoded. |
| 513 |
*/ |
| 514 |
goog.string.urlEncode = function(str) { |
| 515 |
return encodeURIComponent(String(str)); |
| 516 |
}; |
| 517 |
|
| 518 |
|
| 519 |
/** |
| 520 |
* URL-decodes the string. We need to specially handle '+'s because |
| 521 |
* the javascript library doesn't convert them to spaces. |
| 522 |
* @param {string} str The string to url decode. |
| 523 |
* @return {string} The decoded {@code str}. |
| 524 |
*/ |
| 525 |
goog.string.urlDecode = function(str) { |
| 526 |
return decodeURIComponent(str.replace(/\+/g, ' ')); |
| 527 |
}; |
| 528 |
|
| 529 |
|
| 530 |
/** |
| 531 |
* Converts \n to <br>s or <br />s. |
| 532 |
* @param {string} str The string in which to convert newlines. |
| 533 |
* @param {boolean=} opt_xml Whether to use XML compatible tags. |
| 534 |
* @return {string} A copy of {@code str} with converted newlines. |
| 535 |
*/ |
| 536 |
goog.string.newLineToBr = function(str, opt_xml) { |
| 537 |
return str.replace(/(\r\n|\r|\n)/g, opt_xml ? '<br />' : '<br>'); |
| 538 |
}; |
| 539 |
|
| 540 |
|
| 541 |
/** |
| 542 |
* Escapes double quote '"' and single quote '\'' characters in addition to |
| 543 |
* '&', '<', and '>' so that a string can be included in an HTML tag attribute |
| 544 |
* value within double or single quotes. |
| 545 |
* |
| 546 |
* It should be noted that > doesn't need to be escaped for the HTML or XML to |
| 547 |
* be valid, but it has been decided to escape it for consistency with other |
| 548 |
* implementations. |
| 549 |
* |
| 550 |
* With goog.string.DETECT_DOUBLE_ESCAPING, this function escapes also the |
| 551 |
* lowercase letter "e". |
| 552 |
* |
| 553 |
* NOTE(user): |
| 554 |
* HtmlEscape is often called during the generation of large blocks of HTML. |
| 555 |
* Using statics for the regular expressions and strings is an optimization |
| 556 |
* that can more than half the amount of time IE spends in this function for |
| 557 |
* large apps, since strings and regexes both contribute to GC allocations. |
| 558 |
* |
| 559 |
* Testing for the presence of a character before escaping increases the number |
| 560 |
* of function calls, but actually provides a speed increase for the average |
| 561 |
* case -- since the average case often doesn't require the escaping of all 4 |
| 562 |
* characters and indexOf() is much cheaper than replace(). |
| 563 |
* The worst case does suffer slightly from the additional calls, therefore the |
| 564 |
* opt_isLikelyToContainHtmlChars option has been included for situations |
| 565 |
* where all 4 HTML entities are very likely to be present and need escaping. |
| 566 |
* |
| 567 |
* Some benchmarks (times tended to fluctuate +-0.05ms): |
| 568 |
* FireFox IE6 |
| 569 |
* (no chars / average (mix of cases) / all 4 chars) |
| 570 |
* no checks 0.13 / 0.22 / 0.22 0.23 / 0.53 / 0.80 |
| 571 |
* indexOf 0.08 / 0.17 / 0.26 0.22 / 0.54 / 0.84 |
| 572 |
* indexOf + re test 0.07 / 0.17 / 0.28 0.19 / 0.50 / 0.85 |
| 573 |
* |
| 574 |
* An additional advantage of checking if replace actually needs to be called |
| 575 |
* is a reduction in the number of object allocations, so as the size of the |
| 576 |
* application grows the difference between the various methods would increase. |
| 577 |
* |
| 578 |
* @param {string} str string to be escaped. |
| 579 |
* @param {boolean=} opt_isLikelyToContainHtmlChars Don't perform a check to see |
| 580 |
* if the character needs replacing - use this option if you expect each of |
| 581 |
* the characters to appear often. Leave false if you expect few html |
| 582 |
* characters to occur in your strings, such as if you are escaping HTML. |
| 583 |
* @return {string} An escaped copy of {@code str}. |
| 584 |
*/ |
| 585 |
goog.string.htmlEscape = function(str, opt_isLikelyToContainHtmlChars) { |
| 586 |
|
| 587 |
if (opt_isLikelyToContainHtmlChars) { |
| 588 |
str = str.replace(goog.string.AMP_RE_, '&') |
| 589 |
.replace(goog.string.LT_RE_, '<') |
| 590 |
.replace(goog.string.GT_RE_, '>') |
| 591 |
.replace(goog.string.QUOT_RE_, '"') |
| 592 |
.replace(goog.string.SINGLE_QUOTE_RE_, ''') |
| 593 |
.replace(goog.string.NULL_RE_, '�'); |
| 594 |
if (goog.string.DETECT_DOUBLE_ESCAPING) { |
| 595 |
str = str.replace(goog.string.E_RE_, 'e'); |
| 596 |
} |
| 597 |
return str; |
| 598 |
|
| 599 |
} else { |
| 600 |
// quick test helps in the case when there are no chars to replace, in |
| 601 |
// worst case this makes barely a difference to the time taken |
| 602 |
if (!goog.string.ALL_RE_.test(str)) return str; |
| 603 |
|
| 604 |
// str.indexOf is faster than regex.test in this case |
| 605 |
if (str.indexOf('&') != -1) { |
| 606 |
str = str.replace(goog.string.AMP_RE_, '&'); |
| 607 |
} |
| 608 |
if (str.indexOf('<') != -1) { |
| 609 |
str = str.replace(goog.string.LT_RE_, '<'); |
| 610 |
} |
| 611 |
if (str.indexOf('>') != -1) { |
| 612 |
str = str.replace(goog.string.GT_RE_, '>'); |
| 613 |
} |
| 614 |
if (str.indexOf('"') != -1) { |
| 615 |
str = str.replace(goog.string.QUOT_RE_, '"'); |
| 616 |
} |
| 617 |
if (str.indexOf('\'') != -1) { |
| 618 |
str = str.replace(goog.string.SINGLE_QUOTE_RE_, '''); |
| 619 |
} |
| 620 |
if (str.indexOf('\x00') != -1) { |
| 621 |
str = str.replace(goog.string.NULL_RE_, '�'); |
| 622 |
} |
| 623 |
if (goog.string.DETECT_DOUBLE_ESCAPING && str.indexOf('e') != -1) { |
| 624 |
str = str.replace(goog.string.E_RE_, 'e'); |
| 625 |
} |
| 626 |
return str; |
| 627 |
} |
| 628 |
}; |
| 629 |
|
| 630 |
|
| 631 |
/** |
| 632 |
* Regular expression that matches an ampersand, for use in escaping. |
| 633 |
* @const {!RegExp} |
| 634 |
* @private |
| 635 |
*/ |
| 636 |
goog.string.AMP_RE_ = /&/g; |
| 637 |
|
| 638 |
|
| 639 |
/** |
| 640 |
* Regular expression that matches a less than sign, for use in escaping. |
| 641 |
* @const {!RegExp} |
| 642 |
* @private |
| 643 |
*/ |
| 644 |
goog.string.LT_RE_ = /</g; |
| 645 |
|
| 646 |
|
| 647 |
/** |
| 648 |
* Regular expression that matches a greater than sign, for use in escaping. |
| 649 |
* @const {!RegExp} |
| 650 |
* @private |
| 651 |
*/ |
| 652 |
goog.string.GT_RE_ = />/g; |
| 653 |
|
| 654 |
|
| 655 |
/** |
| 656 |
* Regular expression that matches a double quote, for use in escaping. |
| 657 |
* @const {!RegExp} |
| 658 |
* @private |
| 659 |
*/ |
| 660 |
goog.string.QUOT_RE_ = /"/g; |
| 661 |
|
| 662 |
|
| 663 |
/** |
| 664 |
* Regular expression that matches a single quote, for use in escaping. |
| 665 |
* @const {!RegExp} |
| 666 |
* @private |
| 667 |
*/ |
| 668 |
goog.string.SINGLE_QUOTE_RE_ = /'/g; |
| 669 |
|
| 670 |
|
| 671 |
/** |
| 672 |
* Regular expression that matches null character, for use in escaping. |
| 673 |
* @const {!RegExp} |
| 674 |
* @private |
| 675 |
*/ |
| 676 |
goog.string.NULL_RE_ = /\x00/g; |
| 677 |
|
| 678 |
|
| 679 |
/** |
| 680 |
* Regular expression that matches a lowercase letter "e", for use in escaping. |
| 681 |
* @const {!RegExp} |
| 682 |
* @private |
| 683 |
*/ |
| 684 |
goog.string.E_RE_ = /e/g; |
| 685 |
|
| 686 |
|
| 687 |
/** |
| 688 |
* Regular expression that matches any character that needs to be escaped. |
| 689 |
* @const {!RegExp} |
| 690 |
* @private |
| 691 |
*/ |
| 692 |
goog.string.ALL_RE_ = |
| 693 |
(goog.string.DETECT_DOUBLE_ESCAPING ? /[\x00&<>"'e]/ : /[\x00&<>"']/); |
| 694 |
|
| 695 |
|
| 696 |
/** |
| 697 |
* Unescapes an HTML string. |
| 698 |
* |
| 699 |
* @param {string} str The string to unescape. |
| 700 |
* @return {string} An unescaped copy of {@code str}. |
| 701 |
*/ |
| 702 |
goog.string.unescapeEntities = function(str) { |
| 703 |
if (goog.string.contains(str, '&')) { |
| 704 |
// We are careful not to use a DOM if we do not have one or we explicitly |
| 705 |
// requested non-DOM html unescaping. |
| 706 |
if (!goog.string.FORCE_NON_DOM_HTML_UNESCAPING && |
| 707 |
'document' in goog.global) { |
| 708 |
return goog.string.unescapeEntitiesUsingDom_(str); |
| 709 |
} else { |
| 710 |
// Fall back on pure XML entities |
| 711 |
return goog.string.unescapePureXmlEntities_(str); |
| 712 |
} |
| 713 |
} |
| 714 |
return str; |
| 715 |
}; |
| 716 |
|
| 717 |
|
| 718 |
/** |
| 719 |
* Unescapes a HTML string using the provided document. |
| 720 |
* |
| 721 |
* @param {string} str The string to unescape. |
| 722 |
* @param {!Document} document A document to use in escaping the string. |
| 723 |
* @return {string} An unescaped copy of {@code str}. |
| 724 |
*/ |
| 725 |
goog.string.unescapeEntitiesWithDocument = function(str, document) { |
| 726 |
if (goog.string.contains(str, '&')) { |
| 727 |
return goog.string.unescapeEntitiesUsingDom_(str, document); |
| 728 |
} |
| 729 |
return str; |
| 730 |
}; |
| 731 |
|
| 732 |
|
| 733 |
/** |
| 734 |
* Unescapes an HTML string using a DOM to resolve non-XML, non-numeric |
| 735 |
* entities. This function is XSS-safe and whitespace-preserving. |
| 736 |
* @private |
| 737 |
* @param {string} str The string to unescape. |
| 738 |
* @param {Document=} opt_document An optional document to use for creating |
| 739 |
* elements. If this is not specified then the default window.document |
| 740 |
* will be used. |
| 741 |
* @return {string} The unescaped {@code str} string. |
| 742 |
*/ |
| 743 |
goog.string.unescapeEntitiesUsingDom_ = function(str, opt_document) { |
| 744 |
/** @type {!Object<string, string>} */ |
| 745 |
var seen = {'&': '&', '<': '<', '>': '>', '"': '"'}; |
| 746 |
var div; |
| 747 |
if (opt_document) { |
| 748 |
div = opt_document.createElement('div'); |
| 749 |
} else { |
| 750 |
div = goog.global.document.createElement('div'); |
| 751 |
} |
| 752 |
// Match as many valid entity characters as possible. If the actual entity |
| 753 |
// happens to be shorter, it will still work as innerHTML will return the |
| 754 |
// trailing characters unchanged. Since the entity characters do not include |
| 755 |
// open angle bracket, there is no chance of XSS from the innerHTML use. |
| 756 |
// Since no whitespace is passed to innerHTML, whitespace is preserved. |
| 757 |
return str.replace(goog.string.HTML_ENTITY_PATTERN_, function(s, entity) { |
| 758 |
// Check for cached entity. |
| 759 |
var value = seen[s]; |
| 760 |
if (value) { |
| 761 |
return value; |
| 762 |
} |
| 763 |
// Check for numeric entity. |
| 764 |
if (entity.charAt(0) == '#') { |
| 765 |
// Prefix with 0 so that hex entities (e.g. ) parse as hex numbers. |
| 766 |
var n = Number('0' + entity.substr(1)); |
| 767 |
if (!isNaN(n)) { |
| 768 |
value = String.fromCharCode(n); |
| 769 |
} |
| 770 |
} |
| 771 |
// Fall back to innerHTML otherwise. |
| 772 |
if (!value) { |
| 773 |
// Append a non-entity character to avoid a bug in Webkit that parses |
| 774 |
// an invalid entity at the end of innerHTML text as the empty string. |
| 775 |
div.innerHTML = s + ' '; |
| 776 |
// Then remove the trailing character from the result. |
| 777 |
value = div.firstChild.nodeValue.slice(0, -1); |
| 778 |
} |
| 779 |
// Cache and return. |
| 780 |
return seen[s] = value; |
| 781 |
}); |
| 782 |
}; |
| 783 |
|
| 784 |
|
| 785 |
/** |
| 786 |
* Unescapes XML entities. |
| 787 |
* @private |
| 788 |
* @param {string} str The string to unescape. |
| 789 |
* @return {string} An unescaped copy of {@code str}. |
| 790 |
*/ |
| 791 |
goog.string.unescapePureXmlEntities_ = function(str) { |
| 792 |
return str.replace(/&([^;]+);/g, function(s, entity) { |
| 793 |
switch (entity) { |
| 794 |
case 'amp': |
| 795 |
return '&'; |
| 796 |
case 'lt': |
| 797 |
return '<'; |
| 798 |
case 'gt': |
| 799 |
return '>'; |
| 800 |
case 'quot': |
| 801 |
return '"'; |
| 802 |
default: |
| 803 |
if (entity.charAt(0) == '#') { |
| 804 |
// Prefix with 0 so that hex entities (e.g. ) parse as hex. |
| 805 |
var n = Number('0' + entity.substr(1)); |
| 806 |
if (!isNaN(n)) { |
| 807 |
return String.fromCharCode(n); |
| 808 |
} |
| 809 |
} |
| 810 |
// For invalid entities we just return the entity |
| 811 |
return s; |
| 812 |
} |
| 813 |
}); |
| 814 |
}; |
| 815 |
|
| 816 |
|
| 817 |
/** |
| 818 |
* Regular expression that matches an HTML entity. |
| 819 |
* See also HTML5: Tokenization / Tokenizing character references. |
| 820 |
* @private |
| 821 |
* @type {!RegExp} |
| 822 |
*/ |
| 823 |
goog.string.HTML_ENTITY_PATTERN_ = /&([^;\s<&]+);?/g; |
| 824 |
|
| 825 |
|
| 826 |
/** |
| 827 |
* Do escaping of whitespace to preserve spatial formatting. We use character |
| 828 |
* entity #160 to make it safer for xml. |
| 829 |
* @param {string} str The string in which to escape whitespace. |
| 830 |
* @param {boolean=} opt_xml Whether to use XML compatible tags. |
| 831 |
* @return {string} An escaped copy of {@code str}. |
| 832 |
*/ |
| 833 |
goog.string.whitespaceEscape = function(str, opt_xml) { |
| 834 |
// This doesn't use goog.string.preserveSpaces for backwards compatibility. |
| 835 |
return goog.string.newLineToBr(str.replace(/ /g, '  '), opt_xml); |
| 836 |
}; |
| 837 |
|
| 838 |
|
| 839 |
/** |
| 840 |
* Preserve spaces that would be otherwise collapsed in HTML by replacing them |
| 841 |
* with non-breaking space Unicode characters. |
| 842 |
* @param {string} str The string in which to preserve whitespace. |
| 843 |
* @return {string} A copy of {@code str} with preserved whitespace. |
| 844 |
*/ |
| 845 |
goog.string.preserveSpaces = function(str) { |
| 846 |
return str.replace(/(^|[\n ]) /g, '$1' + goog.string.Unicode.NBSP); |
| 847 |
}; |
| 848 |
|
| 849 |
|
| 850 |
/** |
| 851 |
* Strip quote characters around a string. The second argument is a string of |
| 852 |
* characters to treat as quotes. This can be a single character or a string of |
| 853 |
* multiple character and in that case each of those are treated as possible |
| 854 |
* quote characters. For example: |
| 855 |
* |
| 856 |
* <pre> |
| 857 |
* goog.string.stripQuotes('"abc"', '"`') --> 'abc' |
| 858 |
* goog.string.stripQuotes('`abc`', '"`') --> 'abc' |
| 859 |
* </pre> |
| 860 |
* |
| 861 |
* @param {string} str The string to strip. |
| 862 |
* @param {string} quoteChars The quote characters to strip. |
| 863 |
* @return {string} A copy of {@code str} without the quotes. |
| 864 |
*/ |
| 865 |
goog.string.stripQuotes = function(str, quoteChars) { |
| 866 |
var length = quoteChars.length; |
| 867 |
for (var i = 0; i < length; i++) { |
| 868 |
var quoteChar = length == 1 ? quoteChars : quoteChars.charAt(i); |
| 869 |
if (str.charAt(0) == quoteChar && str.charAt(str.length - 1) == quoteChar) { |
| 870 |
return str.substring(1, str.length - 1); |
| 871 |
} |
| 872 |
} |
| 873 |
return str; |
| 874 |
}; |
| 875 |
|
| 876 |
|
| 877 |
/** |
| 878 |
* Truncates a string to a certain length and adds '...' if necessary. The |
| 879 |
* length also accounts for the ellipsis, so a maximum length of 10 and a string |
| 880 |
* 'Hello World!' produces 'Hello W...'. |
| 881 |
* @param {string} str The string to truncate. |
| 882 |
* @param {number} chars Max number of characters. |
| 883 |
* @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped |
| 884 |
* characters from being cut off in the middle. |
| 885 |
* @return {string} The truncated {@code str} string. |
| 886 |
*/ |
| 887 |
goog.string.truncate = function(str, chars, opt_protectEscapedCharacters) { |
| 888 |
if (opt_protectEscapedCharacters) { |
| 889 |
str = goog.string.unescapeEntities(str); |
| 890 |
} |
| 891 |
|
| 892 |
if (str.length > chars) { |
| 893 |
str = str.substring(0, chars - 3) + '...'; |
| 894 |
} |
| 895 |
|
| 896 |
if (opt_protectEscapedCharacters) { |
| 897 |
str = goog.string.htmlEscape(str); |
| 898 |
} |
| 899 |
|
| 900 |
return str; |
| 901 |
}; |
| 902 |
|
| 903 |
|
| 904 |
/** |
| 905 |
* Truncate a string in the middle, adding "..." if necessary, |
| 906 |
* and favoring the beginning of the string. |
| 907 |
* @param {string} str The string to truncate the middle of. |
| 908 |
* @param {number} chars Max number of characters. |
| 909 |
* @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped |
| 910 |
* characters from being cutoff in the middle. |
| 911 |
* @param {number=} opt_trailingChars Optional number of trailing characters to |
| 912 |
* leave at the end of the string, instead of truncating as close to the |
| 913 |
* middle as possible. |
| 914 |
* @return {string} A truncated copy of {@code str}. |
| 915 |
*/ |
| 916 |
goog.string.truncateMiddle = function( |
| 917 |
str, chars, opt_protectEscapedCharacters, opt_trailingChars) { |
| 918 |
if (opt_protectEscapedCharacters) { |
| 919 |
str = goog.string.unescapeEntities(str); |
| 920 |
} |
| 921 |
|
| 922 |
if (opt_trailingChars && str.length > chars) { |
| 923 |
if (opt_trailingChars > chars) { |
| 924 |
opt_trailingChars = chars; |
| 925 |
} |
| 926 |
var endPoint = str.length - opt_trailingChars; |
| 927 |
var startPoint = chars - opt_trailingChars; |
| 928 |
str = str.substring(0, startPoint) + '...' + str.substring(endPoint); |
| 929 |
} else if (str.length > chars) { |
| 930 |
// Favor the beginning of the string: |
| 931 |
var half = Math.floor(chars / 2); |
| 932 |
var endPos = str.length - half; |
| 933 |
half += chars % 2; |
| 934 |
str = str.substring(0, half) + '...' + str.substring(endPos); |
| 935 |
} |
| 936 |
|
| 937 |
if (opt_protectEscapedCharacters) { |
| 938 |
str = goog.string.htmlEscape(str); |
| 939 |
} |
| 940 |
|
| 941 |
return str; |
| 942 |
}; |
| 943 |
|
| 944 |
|
| 945 |
/** |
| 946 |
* Special chars that need to be escaped for goog.string.quote. |
| 947 |
* @private {!Object<string, string>} |
| 948 |
*/ |
| 949 |
goog.string.specialEscapeChars_ = { |
| 950 |
'\0': '\\0', |
| 951 |
'\b': '\\b', |
| 952 |
'\f': '\\f', |
| 953 |
'\n': '\\n', |
| 954 |
'\r': '\\r', |
| 955 |
'\t': '\\t', |
| 956 |
'\x0B': '\\x0B', // '\v' is not supported in JScript |
| 957 |
'"': '\\"', |
| 958 |
'\\': '\\\\', |
| 959 |
// To support the use case of embedding quoted strings inside of script |
| 960 |
// tags, we have to make sure HTML comments and opening/closing script tags do |
| 961 |
// not appear in the resulting string. The specific strings that must be |
| 962 |
// escaped are documented at: |
| 963 |
// http://www.w3.org/TR/html51/semantics.html#restrictions-for-contents-of-script-elements |
| 964 |
'<': '\x3c' |
| 965 |
}; |
| 966 |
|
| 967 |
|
| 968 |
/** |
| 969 |
* Character mappings used internally for goog.string.escapeChar. |
| 970 |
* @private {!Object<string, string>} |
| 971 |
*/ |
| 972 |
goog.string.jsEscapeCache_ = { |
| 973 |
'\'': '\\\'' |
| 974 |
}; |
| 975 |
|
| 976 |
|
| 977 |
/** |
| 978 |
* Encloses a string in double quotes and escapes characters so that the |
| 979 |
* string is a valid JS string. The resulting string is safe to embed in |
| 980 |
* `<script>` tags as "<" is escaped. |
| 981 |
* @param {string} s The string to quote. |
| 982 |
* @return {string} A copy of {@code s} surrounded by double quotes. |
| 983 |
*/ |
| 984 |
goog.string.quote = function(s) { |
| 985 |
s = String(s); |
| 986 |
var sb = ['"']; |
| 987 |
for (var i = 0; i < s.length; i++) { |
| 988 |
var ch = s.charAt(i); |
| 989 |
var cc = ch.charCodeAt(0); |
| 990 |
sb[i + 1] = goog.string.specialEscapeChars_[ch] || |
| 991 |
((cc > 31 && cc < 127) ? ch : goog.string.escapeChar(ch)); |
| 992 |
} |
| 993 |
sb.push('"'); |
| 994 |
return sb.join(''); |
| 995 |
}; |
| 996 |
|
| 997 |
|
| 998 |
/** |
| 999 |
* Takes a string and returns the escaped string for that input string. |
| 1000 |
* @param {string} str The string to escape. |
| 1001 |
* @return {string} An escaped string representing {@code str}. |
| 1002 |
*/ |
| 1003 |
goog.string.escapeString = function(str) { |
| 1004 |
var sb = []; |
| 1005 |
for (var i = 0; i < str.length; i++) { |
| 1006 |
sb[i] = goog.string.escapeChar(str.charAt(i)); |
| 1007 |
} |
| 1008 |
return sb.join(''); |
| 1009 |
}; |
| 1010 |
|
| 1011 |
|
| 1012 |
/** |
| 1013 |
* Takes a character and returns the escaped string for that character. For |
| 1014 |
* example escapeChar(String.fromCharCode(15)) -> "\\x0E". |
| 1015 |
* @param {string} c The character to escape. |
| 1016 |
* @return {string} An escaped string representing {@code c}. |
| 1017 |
*/ |
| 1018 |
goog.string.escapeChar = function(c) { |
| 1019 |
if (c in goog.string.jsEscapeCache_) { |
| 1020 |
return goog.string.jsEscapeCache_[c]; |
| 1021 |
} |
| 1022 |
|
| 1023 |
if (c in goog.string.specialEscapeChars_) { |
| 1024 |
return goog.string.jsEscapeCache_[c] = goog.string.specialEscapeChars_[c]; |
| 1025 |
} |
| 1026 |
|
| 1027 |
var rv = c; |
| 1028 |
var cc = c.charCodeAt(0); |
| 1029 |
if (cc > 31 && cc < 127) { |
| 1030 |
rv = c; |
| 1031 |
} else { |
| 1032 |
// tab is 9 but handled above |
| 1033 |
if (cc < 256) { |
| 1034 |
rv = '\\x'; |
| 1035 |
if (cc < 16 || cc > 256) { |
| 1036 |
rv += '0'; |
| 1037 |
} |
| 1038 |
} else { |
| 1039 |
rv = '\\u'; |
| 1040 |
if (cc < 4096) { // \u1000 |
| 1041 |
rv += '0'; |
| 1042 |
} |
| 1043 |
} |
| 1044 |
rv += cc.toString(16).toUpperCase(); |
| 1045 |
} |
| 1046 |
|
| 1047 |
return goog.string.jsEscapeCache_[c] = rv; |
| 1048 |
}; |
| 1049 |
|
| 1050 |
|
| 1051 |
/** |
| 1052 |
* Determines whether a string contains a substring. |
| 1053 |
* @param {string} str The string to search. |
| 1054 |
* @param {string} subString The substring to search for. |
| 1055 |
* @return {boolean} Whether {@code str} contains {@code subString}. |
| 1056 |
*/ |
| 1057 |
goog.string.contains = function(str, subString) { |
| 1058 |
return str.indexOf(subString) != -1; |
| 1059 |
}; |
| 1060 |
|
| 1061 |
|
| 1062 |
/** |
| 1063 |
* Determines whether a string contains a substring, ignoring case. |
| 1064 |
* @param {string} str The string to search. |
| 1065 |
* @param {string} subString The substring to search for. |
| 1066 |
* @return {boolean} Whether {@code str} contains {@code subString}. |
| 1067 |
*/ |
| 1068 |
goog.string.caseInsensitiveContains = function(str, subString) { |
| 1069 |
return goog.string.contains(str.toLowerCase(), subString.toLowerCase()); |
| 1070 |
}; |
| 1071 |
|
| 1072 |
|
| 1073 |
/** |
| 1074 |
* Returns the non-overlapping occurrences of ss in s. |
| 1075 |
* If either s or ss evalutes to false, then returns zero. |
| 1076 |
* @param {string} s The string to look in. |
| 1077 |
* @param {string} ss The string to look for. |
| 1078 |
* @return {number} Number of occurrences of ss in s. |
| 1079 |
*/ |
| 1080 |
goog.string.countOf = function(s, ss) { |
| 1081 |
return s && ss ? s.split(ss).length - 1 : 0; |
| 1082 |
}; |
| 1083 |
|
| 1084 |
|
| 1085 |
/** |
| 1086 |
* Removes a substring of a specified length at a specific |
| 1087 |
* index in a string. |
| 1088 |
* @param {string} s The base string from which to remove. |
| 1089 |
* @param {number} index The index at which to remove the substring. |
| 1090 |
* @param {number} stringLength The length of the substring to remove. |
| 1091 |
* @return {string} A copy of {@code s} with the substring removed or the full |
| 1092 |
* string if nothing is removed or the input is invalid. |
| 1093 |
*/ |
| 1094 |
goog.string.removeAt = function(s, index, stringLength) { |
| 1095 |
var resultStr = s; |
| 1096 |
// If the index is greater or equal to 0 then remove substring |
| 1097 |
if (index >= 0 && index < s.length && stringLength > 0) { |
| 1098 |
resultStr = s.substr(0, index) + |
| 1099 |
s.substr(index + stringLength, s.length - index - stringLength); |
| 1100 |
} |
| 1101 |
return resultStr; |
| 1102 |
}; |
| 1103 |
|
| 1104 |
|
| 1105 |
/** |
| 1106 |
* Removes the first occurrence of a substring from a string. |
| 1107 |
* @param {string} str The base string from which to remove. |
| 1108 |
* @param {string} substr The string to remove. |
| 1109 |
* @return {string} A copy of {@code str} with {@code substr} removed or the |
| 1110 |
* full string if nothing is removed. |
| 1111 |
*/ |
| 1112 |
goog.string.remove = function(str, substr) { |
| 1113 |
return str.replace(substr, ''); |
| 1114 |
}; |
| 1115 |
|
| 1116 |
|
| 1117 |
/** |
| 1118 |
* Removes all occurrences of a substring from a string. |
| 1119 |
* @param {string} s The base string from which to remove. |
| 1120 |
* @param {string} ss The string to remove. |
| 1121 |
* @return {string} A copy of {@code s} with {@code ss} removed or the full |
| 1122 |
* string if nothing is removed. |
| 1123 |
*/ |
| 1124 |
goog.string.removeAll = function(s, ss) { |
| 1125 |
var re = new RegExp(goog.string.regExpEscape(ss), 'g'); |
| 1126 |
return s.replace(re, ''); |
| 1127 |
}; |
| 1128 |
|
| 1129 |
|
| 1130 |
/** |
| 1131 |
* Replaces all occurrences of a substring of a string with a new substring. |
| 1132 |
* @param {string} s The base string from which to remove. |
| 1133 |
* @param {string} ss The string to replace. |
| 1134 |
* @param {string} replacement The replacement string. |
| 1135 |
* @return {string} A copy of {@code s} with {@code ss} replaced by |
| 1136 |
* {@code replacement} or the original string if nothing is replaced. |
| 1137 |
*/ |
| 1138 |
goog.string.replaceAll = function(s, ss, replacement) { |
| 1139 |
var re = new RegExp(goog.string.regExpEscape(ss), 'g'); |
| 1140 |
return s.replace(re, replacement.replace(/\$/g, '$$$$')); |
| 1141 |
}; |
| 1142 |
|
| 1143 |
|
| 1144 |
/** |
| 1145 |
* Escapes characters in the string that are not safe to use in a RegExp. |
| 1146 |
* @param {*} s The string to escape. If not a string, it will be casted |
| 1147 |
* to one. |
| 1148 |
* @return {string} A RegExp safe, escaped copy of {@code s}. |
| 1149 |
*/ |
| 1150 |
goog.string.regExpEscape = function(s) { |
| 1151 |
return String(s) |
| 1152 |
.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1') |
| 1153 |
.replace(/\x08/g, '\\x08'); |
| 1154 |
}; |
| 1155 |
|
| 1156 |
|
| 1157 |
/** |
| 1158 |
* Repeats a string n times. |
| 1159 |
* @param {string} string The string to repeat. |
| 1160 |
* @param {number} length The number of times to repeat. |
| 1161 |
* @return {string} A string containing {@code length} repetitions of |
| 1162 |
* {@code string}. |
| 1163 |
*/ |
| 1164 |
goog.string.repeat = (String.prototype.repeat) ? function(string, length) { |
| 1165 |
// The native method is over 100 times faster than the alternative. |
| 1166 |
return string.repeat(length); |
| 1167 |
} : function(string, length) { |
| 1168 |
return new Array(length + 1).join(string); |
| 1169 |
}; |
| 1170 |
|
| 1171 |
|
| 1172 |
/** |
| 1173 |
* Pads number to given length and optionally rounds it to a given precision. |
| 1174 |
* For example: |
| 1175 |
* <pre>padNumber(1.25, 2, 3) -> '01.250' |
| 1176 |
* padNumber(1.25, 2) -> '01.25' |
| 1177 |
* padNumber(1.25, 2, 1) -> '01.3' |
| 1178 |
* padNumber(1.25, 0) -> '1.25'</pre> |
| 1179 |
* |
| 1180 |
* @param {number} num The number to pad. |
| 1181 |
* @param {number} length The desired length. |
| 1182 |
* @param {number=} opt_precision The desired precision. |
| 1183 |
* @return {string} {@code num} as a string with the given options. |
| 1184 |
*/ |
| 1185 |
goog.string.padNumber = function(num, length, opt_precision) { |
| 1186 |
var s = goog.isDef(opt_precision) ? num.toFixed(opt_precision) : String(num); |
| 1187 |
var index = s.indexOf('.'); |
| 1188 |
if (index == -1) { |
| 1189 |
index = s.length; |
| 1190 |
} |
| 1191 |
return goog.string.repeat('0', Math.max(0, length - index)) + s; |
| 1192 |
}; |
| 1193 |
|
| 1194 |
|
| 1195 |
/** |
| 1196 |
* Returns a string representation of the given object, with |
| 1197 |
* null and undefined being returned as the empty string. |
| 1198 |
* |
| 1199 |
* @param {*} obj The object to convert. |
| 1200 |
* @return {string} A string representation of the {@code obj}. |
| 1201 |
*/ |
| 1202 |
goog.string.makeSafe = function(obj) { |
| 1203 |
return obj == null ? '' : String(obj); |
| 1204 |
}; |
| 1205 |
|
| 1206 |
|
| 1207 |
/** |
| 1208 |
* Concatenates string expressions. This is useful |
| 1209 |
* since some browsers are very inefficient when it comes to using plus to |
| 1210 |
* concat strings. Be careful when using null and undefined here since |
| 1211 |
* these will not be included in the result. If you need to represent these |
| 1212 |
* be sure to cast the argument to a String first. |
| 1213 |
* For example: |
| 1214 |
* <pre>buildString('a', 'b', 'c', 'd') -> 'abcd' |
| 1215 |
* buildString(null, undefined) -> '' |
| 1216 |
* </pre> |
| 1217 |
* @param {...*} var_args A list of strings to concatenate. If not a string, |
| 1218 |
* it will be casted to one. |
| 1219 |
* @return {string} The concatenation of {@code var_args}. |
| 1220 |
*/ |
| 1221 |
goog.string.buildString = function(var_args) { |
| 1222 |
return Array.prototype.join.call(arguments, ''); |
| 1223 |
}; |
| 1224 |
|
| 1225 |
|
| 1226 |
/** |
| 1227 |
* Returns a string with at least 64-bits of randomness. |
| 1228 |
* |
| 1229 |
* Doesn't trust Javascript's random function entirely. Uses a combination of |
| 1230 |
* random and current timestamp, and then encodes the string in base-36 to |
| 1231 |
* make it shorter. |
| 1232 |
* |
| 1233 |
* @return {string} A random string, e.g. sn1s7vb4gcic. |
| 1234 |
*/ |
| 1235 |
goog.string.getRandomString = function() { |
| 1236 |
var x = 2147483648; |
| 1237 |
return Math.floor(Math.random() * x).toString(36) + |
| 1238 |
Math.abs(Math.floor(Math.random() * x) ^ goog.now()).toString(36); |
| 1239 |
}; |
| 1240 |
|
| 1241 |
|
| 1242 |
/** |
| 1243 |
* Compares two version numbers. |
| 1244 |
* |
| 1245 |
* @param {string|number} version1 Version of first item. |
| 1246 |
* @param {string|number} version2 Version of second item. |
| 1247 |
* |
| 1248 |
* @return {number} 1 if {@code version1} is higher. |
| 1249 |
* 0 if arguments are equal. |
| 1250 |
* -1 if {@code version2} is higher. |
| 1251 |
*/ |
| 1252 |
goog.string.compareVersions = function(version1, version2) { |
| 1253 |
var order = 0; |
| 1254 |
// Trim leading and trailing whitespace and split the versions into |
| 1255 |
// subversions. |
| 1256 |
var v1Subs = goog.string.trim(String(version1)).split('.'); |
| 1257 |
var v2Subs = goog.string.trim(String(version2)).split('.'); |
| 1258 |
var subCount = Math.max(v1Subs.length, v2Subs.length); |
| 1259 |
|
| 1260 |
// Iterate over the subversions, as long as they appear to be equivalent. |
| 1261 |
for (var subIdx = 0; order == 0 && subIdx < subCount; subIdx++) { |
| 1262 |
var v1Sub = v1Subs[subIdx] || ''; |
| 1263 |
var v2Sub = v2Subs[subIdx] || ''; |
| 1264 |
|
| 1265 |
do { |
| 1266 |
// Split the subversions into pairs of numbers and qualifiers (like 'b'). |
| 1267 |
// Two different RegExp objects are use to make it clear the code |
| 1268 |
// is side-effect free |
| 1269 |
var v1Comp = /(\d*)(\D*)(.*)/.exec(v1Sub) || ['', '', '', '']; |
| 1270 |
var v2Comp = /(\d*)(\D*)(.*)/.exec(v2Sub) || ['', '', '', '']; |
| 1271 |
// Break if there are no more matches. |
| 1272 |
if (v1Comp[0].length == 0 && v2Comp[0].length == 0) { |
| 1273 |
break; |
| 1274 |
} |
| 1275 |
|
| 1276 |
// Parse the numeric part of the subversion. A missing number is |
| 1277 |
// equivalent to 0. |
| 1278 |
var v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10); |
| 1279 |
var v2CompNum = v2Comp[1].length == 0 ? 0 : parseInt(v2Comp[1], 10); |
| 1280 |
|
| 1281 |
// Compare the subversion components. The number has the highest |
| 1282 |
// precedence. Next, if the numbers are equal, a subversion without any |
| 1283 |
// qualifier is always higher than a subversion with any qualifier. Next, |
| 1284 |
// the qualifiers are compared as strings. |
| 1285 |
order = goog.string.compareElements_(v1CompNum, v2CompNum) || |
| 1286 |
goog.string.compareElements_( |
| 1287 |
v1Comp[2].length == 0, v2Comp[2].length == 0) || |
| 1288 |
goog.string.compareElements_(v1Comp[2], v2Comp[2]); |
| 1289 |
// Stop as soon as an inequality is discovered. |
| 1290 |
|
| 1291 |
v1Sub = v1Comp[3]; |
| 1292 |
v2Sub = v2Comp[3]; |
| 1293 |
} while (order == 0); |
| 1294 |
} |
| 1295 |
|
| 1296 |
return order; |
| 1297 |
}; |
| 1298 |
|
| 1299 |
|
| 1300 |
/** |
| 1301 |
* Compares elements of a version number. |
| 1302 |
* |
| 1303 |
* @param {string|number|boolean} left An element from a version number. |
| 1304 |
* @param {string|number|boolean} right An element from a version number. |
| 1305 |
* |
| 1306 |
* @return {number} 1 if {@code left} is higher. |
| 1307 |
* 0 if arguments are equal. |
| 1308 |
* -1 if {@code right} is higher. |
| 1309 |
* @private |
| 1310 |
*/ |
| 1311 |
goog.string.compareElements_ = function(left, right) { |
| 1312 |
if (left < right) { |
| 1313 |
return -1; |
| 1314 |
} else if (left > right) { |
| 1315 |
return 1; |
| 1316 |
} |
| 1317 |
return 0; |
| 1318 |
}; |
| 1319 |
|
| 1320 |
|
| 1321 |
/** |
| 1322 |
* String hash function similar to java.lang.String.hashCode(). |
| 1323 |
* The hash code for a string is computed as |
| 1324 |
* s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], |
| 1325 |
* where s[i] is the ith character of the string and n is the length of |
| 1326 |
* the string. We mod the result to make it between 0 (inclusive) and 2^32 |
| 1327 |
* (exclusive). |
| 1328 |
* @param {string} str A string. |
| 1329 |
* @return {number} Hash value for {@code str}, between 0 (inclusive) and 2^32 |
| 1330 |
* (exclusive). The empty string returns 0. |
| 1331 |
*/ |
| 1332 |
goog.string.hashCode = function(str) { |
| 1333 |
var result = 0; |
| 1334 |
for (var i = 0; i < str.length; ++i) { |
| 1335 |
// Normalize to 4 byte range, 0 ... 2^32. |
| 1336 |
result = (31 * result + str.charCodeAt(i)) >>> 0; |
| 1337 |
} |
| 1338 |
return result; |
| 1339 |
}; |
| 1340 |
|
| 1341 |
|
| 1342 |
/** |
| 1343 |
* The most recent unique ID. |0 is equivalent to Math.floor in this case. |
| 1344 |
* @type {number} |
| 1345 |
* @private |
| 1346 |
*/ |
| 1347 |
goog.string.uniqueStringCounter_ = Math.random() * 0x80000000 | 0; |
| 1348 |
|
| 1349 |
|
| 1350 |
/** |
| 1351 |
* Generates and returns a string which is unique in the current document. |
| 1352 |
* This is useful, for example, to create unique IDs for DOM elements. |
| 1353 |
* @return {string} A unique id. |
| 1354 |
*/ |
| 1355 |
goog.string.createUniqueString = function() { |
| 1356 |
return 'goog_' + goog.string.uniqueStringCounter_++; |
| 1357 |
}; |
| 1358 |
|
| 1359 |
|
| 1360 |
/** |
| 1361 |
* Converts the supplied string to a number, which may be Infinity or NaN. |
| 1362 |
* This function strips whitespace: (toNumber(' 123') === 123) |
| 1363 |
* This function accepts scientific notation: (toNumber('1e1') === 10) |
| 1364 |
* |
| 1365 |
* This is better than Javascript's built-in conversions because, sadly: |
| 1366 |
* (Number(' ') === 0) and (parseFloat('123a') === 123) |
| 1367 |
* |
| 1368 |
* @param {string} str The string to convert. |
| 1369 |
* @return {number} The number the supplied string represents, or NaN. |
| 1370 |
*/ |
| 1371 |
goog.string.toNumber = function(str) { |
| 1372 |
var num = Number(str); |
| 1373 |
if (num == 0 && goog.string.isEmptyOrWhitespace(str)) { |
| 1374 |
return NaN; |
| 1375 |
} |
| 1376 |
return num; |
| 1377 |
}; |
| 1378 |
|
| 1379 |
|
| 1380 |
/** |
| 1381 |
* Returns whether the given string is lower camel case (e.g. "isFooBar"). |
| 1382 |
* |
| 1383 |
* Note that this assumes the string is entirely letters. |
| 1384 |
* @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms |
| 1385 |
* |
| 1386 |
* @param {string} str String to test. |
| 1387 |
* @return {boolean} Whether the string is lower camel case. |
| 1388 |
*/ |
| 1389 |
goog.string.isLowerCamelCase = function(str) { |
| 1390 |
return /^[a-z]+([A-Z][a-z]*)*$/.test(str); |
| 1391 |
}; |
| 1392 |
|
| 1393 |
|
| 1394 |
/** |
| 1395 |
* Returns whether the given string is upper camel case (e.g. "FooBarBaz"). |
| 1396 |
* |
| 1397 |
* Note that this assumes the string is entirely letters. |
| 1398 |
* @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms |
| 1399 |
* |
| 1400 |
* @param {string} str String to test. |
| 1401 |
* @return {boolean} Whether the string is upper camel case. |
| 1402 |
*/ |
| 1403 |
goog.string.isUpperCamelCase = function(str) { |
| 1404 |
return /^([A-Z][a-z]*)+$/.test(str); |
| 1405 |
}; |
| 1406 |
|
| 1407 |
|
| 1408 |
/** |
| 1409 |
* Converts a string from selector-case to camelCase (e.g. from |
| 1410 |
* "multi-part-string" to "multiPartString"), useful for converting |
| 1411 |
* CSS selectors and HTML dataset keys to their equivalent JS properties. |
| 1412 |
* @param {string} str The string in selector-case form. |
| 1413 |
* @return {string} The string in camelCase form. |
| 1414 |
*/ |
| 1415 |
goog.string.toCamelCase = function(str) { |
| 1416 |
return String(str).replace( |
| 1417 |
/\-([a-z])/g, function(all, match) { return match.toUpperCase(); }); |
| 1418 |
}; |
| 1419 |
|
| 1420 |
|
| 1421 |
/** |
| 1422 |
* Converts a string from camelCase to selector-case (e.g. from |
| 1423 |
* "multiPartString" to "multi-part-string"), useful for converting JS |
| 1424 |
* style and dataset properties to equivalent CSS selectors and HTML keys. |
| 1425 |
* @param {string} str The string in camelCase form. |
| 1426 |
* @return {string} The string in selector-case form. |
| 1427 |
*/ |
| 1428 |
goog.string.toSelectorCase = function(str) { |
| 1429 |
return String(str).replace(/([A-Z])/g, '-$1').toLowerCase(); |
| 1430 |
}; |
| 1431 |
|
| 1432 |
|
| 1433 |
/** |
| 1434 |
* Converts a string into TitleCase. First character of the string is always |
| 1435 |
* capitalized in addition to the first letter of every subsequent word. |
| 1436 |
* Words are delimited by one or more whitespaces by default. Custom delimiters |
| 1437 |
* can optionally be specified to replace the default, which doesn't preserve |
| 1438 |
* whitespace delimiters and instead must be explicitly included if needed. |
| 1439 |
* |
| 1440 |
* Default delimiter => " ": |
| 1441 |
* goog.string.toTitleCase('oneTwoThree') => 'OneTwoThree' |
| 1442 |
* goog.string.toTitleCase('one two three') => 'One Two Three' |
| 1443 |
* goog.string.toTitleCase(' one two ') => ' One Two ' |
| 1444 |
* goog.string.toTitleCase('one_two_three') => 'One_two_three' |
| 1445 |
* goog.string.toTitleCase('one-two-three') => 'One-two-three' |
| 1446 |
* |
| 1447 |
* Custom delimiter => "_-.": |
| 1448 |
* goog.string.toTitleCase('oneTwoThree', '_-.') => 'OneTwoThree' |
| 1449 |
* goog.string.toTitleCase('one two three', '_-.') => 'One two three' |
| 1450 |
* goog.string.toTitleCase(' one two ', '_-.') => ' one two ' |
| 1451 |
* goog.string.toTitleCase('one_two_three', '_-.') => 'One_Two_Three' |
| 1452 |
* goog.string.toTitleCase('one-two-three', '_-.') => 'One-Two-Three' |
| 1453 |
* goog.string.toTitleCase('one...two...three', '_-.') => 'One...Two...Three' |
| 1454 |
* goog.string.toTitleCase('one. two. three', '_-.') => 'One. two. three' |
| 1455 |
* goog.string.toTitleCase('one-two.three', '_-.') => 'One-Two.Three' |
| 1456 |
* |
| 1457 |
* @param {string} str String value in camelCase form. |
| 1458 |
* @param {string=} opt_delimiters Custom delimiter character set used to |
| 1459 |
* distinguish words in the string value. Each character represents a |
| 1460 |
* single delimiter. When provided, default whitespace delimiter is |
| 1461 |
* overridden and must be explicitly included if needed. |
| 1462 |
* @return {string} String value in TitleCase form. |
| 1463 |
*/ |
| 1464 |
goog.string.toTitleCase = function(str, opt_delimiters) { |
| 1465 |
var delimiters = goog.isString(opt_delimiters) ? |
| 1466 |
goog.string.regExpEscape(opt_delimiters) : |
| 1467 |
'\\s'; |
| 1468 |
|
| 1469 |
// For IE8, we need to prevent using an empty character set. Otherwise, |
| 1470 |
// incorrect matching will occur. |
| 1471 |
delimiters = delimiters ? '|[' + delimiters + ']+' : ''; |
| 1472 |
|
| 1473 |
var regexp = new RegExp('(^' + delimiters + ')([a-z])', 'g'); |
| 1474 |
return str.replace( |
| 1475 |
regexp, function(all, p1, p2) { return p1 + p2.toUpperCase(); }); |
| 1476 |
}; |
| 1477 |
|
| 1478 |
|
| 1479 |
/** |
| 1480 |
* Capitalizes a string, i.e. converts the first letter to uppercase |
| 1481 |
* and all other letters to lowercase, e.g.: |
| 1482 |
* |
| 1483 |
* goog.string.capitalize('one') => 'One' |
| 1484 |
* goog.string.capitalize('ONE') => 'One' |
| 1485 |
* goog.string.capitalize('one two') => 'One two' |
| 1486 |
* |
| 1487 |
* Note that this function does not trim initial whitespace. |
| 1488 |
* |
| 1489 |
* @param {string} str String value to capitalize. |
| 1490 |
* @return {string} String value with first letter in uppercase. |
| 1491 |
*/ |
| 1492 |
goog.string.capitalize = function(str) { |
| 1493 |
return String(str.charAt(0)).toUpperCase() + |
| 1494 |
String(str.substr(1)).toLowerCase(); |
| 1495 |
}; |
| 1496 |
|
| 1497 |
|
| 1498 |
/** |
| 1499 |
* Parse a string in decimal or hexidecimal ('0xFFFF') form. |
| 1500 |
* |
| 1501 |
* To parse a particular radix, please use parseInt(string, radix) directly. See |
| 1502 |
* https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt |
| 1503 |
* |
| 1504 |
* This is a wrapper for the built-in parseInt function that will only parse |
| 1505 |
* numbers as base 10 or base 16. Some JS implementations assume strings |
| 1506 |
* starting with "0" are intended to be octal. ES3 allowed but discouraged |
| 1507 |
* this behavior. ES5 forbids it. This function emulates the ES5 behavior. |
| 1508 |
* |
| 1509 |
* For more information, see Mozilla JS Reference: http://goo.gl/8RiFj |
| 1510 |
* |
| 1511 |
* @param {string|number|null|undefined} value The value to be parsed. |
| 1512 |
* @return {number} The number, parsed. If the string failed to parse, this |
| 1513 |
* will be NaN. |
| 1514 |
*/ |
| 1515 |
goog.string.parseInt = function(value) { |
| 1516 |
// Force finite numbers to strings. |
| 1517 |
if (isFinite(value)) { |
| 1518 |
value = String(value); |
| 1519 |
} |
| 1520 |
|
| 1521 |
if (goog.isString(value)) { |
| 1522 |
// If the string starts with '0x' or '-0x', parse as hex. |
| 1523 |
return /^\s*-?0x/i.test(value) ? parseInt(value, 16) : parseInt(value, 10); |
| 1524 |
} |
| 1525 |
|
| 1526 |
return NaN; |
| 1527 |
}; |
| 1528 |
|
| 1529 |
|
| 1530 |
/** |
| 1531 |
* Splits a string on a separator a limited number of times. |
| 1532 |
* |
| 1533 |
* This implementation is more similar to Python or Java, where the limit |
| 1534 |
* parameter specifies the maximum number of splits rather than truncating |
| 1535 |
* the number of results. |
| 1536 |
* |
| 1537 |
* See http://docs.python.org/2/library/stdtypes.html#str.split |
| 1538 |
* See JavaDoc: http://goo.gl/F2AsY |
| 1539 |
* See Mozilla reference: http://goo.gl/dZdZs |
| 1540 |
* |
| 1541 |
* @param {string} str String to split. |
| 1542 |
* @param {string} separator The separator. |
| 1543 |
* @param {number} limit The limit to the number of splits. The resulting array |
| 1544 |
* will have a maximum length of limit+1. Negative numbers are the same |
| 1545 |
* as zero. |
| 1546 |
* @return {!Array<string>} The string, split. |
| 1547 |
*/ |
| 1548 |
goog.string.splitLimit = function(str, separator, limit) { |
| 1549 |
var parts = str.split(separator); |
| 1550 |
var returnVal = []; |
| 1551 |
|
| 1552 |
// Only continue doing this while we haven't hit the limit and we have |
| 1553 |
// parts left. |
| 1554 |
while (limit > 0 && parts.length) { |
| 1555 |
returnVal.push(parts.shift()); |
| 1556 |
limit--; |
| 1557 |
} |
| 1558 |
|
| 1559 |
// If there are remaining parts, append them to the end. |
| 1560 |
if (parts.length) { |
| 1561 |
returnVal.push(parts.join(separator)); |
| 1562 |
} |
| 1563 |
|
| 1564 |
return returnVal; |
| 1565 |
}; |
| 1566 |
|
| 1567 |
|
| 1568 |
/** |
| 1569 |
* Finds the characters to the right of the last instance of any separator |
| 1570 |
* |
| 1571 |
* This function is similar to goog.string.path.baseName, except it can take a |
| 1572 |
* list of characters to split the string on. It will return the rightmost |
| 1573 |
* grouping of characters to the right of any separator as a left-to-right |
| 1574 |
* oriented string. |
| 1575 |
* |
| 1576 |
* @see goog.string.path.baseName |
| 1577 |
* @param {string} str The string |
| 1578 |
* @param {string|!Array<string>} separators A list of separator characters |
| 1579 |
* @return {string} The last part of the string with respect to the separators |
| 1580 |
*/ |
| 1581 |
goog.string.lastComponent = function(str, separators) { |
| 1582 |
if (!separators) { |
| 1583 |
return str; |
| 1584 |
} else if (typeof separators == 'string') { |
| 1585 |
separators = [separators]; |
| 1586 |
} |
| 1587 |
|
| 1588 |
var lastSeparatorIndex = -1; |
| 1589 |
for (var i = 0; i < separators.length; i++) { |
| 1590 |
if (separators[i] == '') { |
| 1591 |
continue; |
| 1592 |
} |
| 1593 |
var currentSeparatorIndex = str.lastIndexOf(separators[i]); |
| 1594 |
if (currentSeparatorIndex > lastSeparatorIndex) { |
| 1595 |
lastSeparatorIndex = currentSeparatorIndex; |
| 1596 |
} |
| 1597 |
} |
| 1598 |
if (lastSeparatorIndex == -1) { |
| 1599 |
return str; |
| 1600 |
} |
| 1601 |
return str.slice(lastSeparatorIndex + 1); |
| 1602 |
}; |
| 1603 |
|
| 1604 |
|
| 1605 |
/** |
| 1606 |
* Computes the Levenshtein edit distance between two strings. |
| 1607 |
* @param {string} a |
| 1608 |
* @param {string} b |
| 1609 |
* @return {number} The edit distance between the two strings. |
| 1610 |
*/ |
| 1611 |
goog.string.editDistance = function(a, b) { |
| 1612 |
var v0 = []; |
| 1613 |
var v1 = []; |
| 1614 |
|
| 1615 |
if (a == b) { |
| 1616 |
return 0; |
| 1617 |
} |
| 1618 |
|
| 1619 |
if (!a.length || !b.length) { |
| 1620 |
return Math.max(a.length, b.length); |
| 1621 |
} |
| 1622 |
|
| 1623 |
for (var i = 0; i < b.length + 1; i++) { |
| 1624 |
v0[i] = i; |
| 1625 |
} |
| 1626 |
|
| 1627 |
for (var i = 0; i < a.length; i++) { |
| 1628 |
v1[0] = i + 1; |
| 1629 |
|
| 1630 |
for (var j = 0; j < b.length; j++) { |
| 1631 |
var cost = Number(a[i] != b[j]); |
| 1632 |
// Cost for the substring is the minimum of adding one character, removing |
| 1633 |
// one character, or a swap. |
| 1634 |
v1[j + 1] = Math.min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost); |
| 1635 |
} |
| 1636 |
|
| 1637 |
for (var j = 0; j < v0.length; j++) { |
| 1638 |
v0[j] = v1[j]; |
| 1639 |
} |
| 1640 |
} |
| 1641 |
|
| 1642 |
return v1[b.length]; |
| 1643 |
}; |