4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
8 <style type="text/css">
9 .highlight { display: block; background-color: #ddd; }
11 <script type="text/javascript">
12 function highlight() {
13 document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
17 <body onload="prettyPrint(); highlight();">
18 <pre class="prettyprint lang-js"><span id='String'>/**
19 </span> * @class String
21 * `String` is a global object that may be used to construct String instances.
23 * String objects may be created by calling the constructor `new String()`. The `String` object wraps
24 * JavaScript's string primitive data type with the methods described below. The global function
25 * `String()` can also be called without new in front to create a primitive string. String literals in
26 * JavaScript are primitive strings.
28 * Because JavaScript automatically converts between string primitives and String objects, you can call
29 * any of the methods of the `String` object on a string primitive. JavaScript automatically converts the
30 * string primitive to a temporary `String` object, calls the method, then discards the temporary String
31 * object. For example, you can use the `String.length` property on a string primitive created from a
34 * s_obj = new String(s_prim = s_also_prim = "foo");
38 * s_also_prim.length; // 3
40 * "foo".length; // 3
42 * (A string literal is denoted with single or double quotation marks.)
44 * String objects can be converted to primitive strings with the `valueOf` method.
46 * String primitives and String objects give different results when evaluated as JavaScript. Primitives
47 * are treated as source code; String objects are treated as a character sequence object. For example:
49 * s1 = "2 + 2"; // creates a string primitive
50 * s2 = new String("2 + 2"); // creates a String object
51 * eval(s1); // returns the number 4
52 * eval(s2); // returns the string "2 + 2"
53 * eval(s2.valueOf()); // returns the number 4
57 * There are two ways to access an individual character in a string. The first is the `charAt` method:
59 * return 'cat'.charAt(1); // returns "a"
61 * The other way is to treat the string as an array, where each index corresponds to an individual
64 * return 'cat'[1]; // returns "a"
66 * The second way (treating the string as an array) is not part of ECMAScript 3. It is a JavaScript and
67 * ECMAScript 5 feature.
69 * In both cases, attempting to set an individual character won't work. Trying to set a character
70 * through `charAt` results in an error, while trying to set a character via indexing does not throw an
71 * error, but the string itself is unchanged.
75 * C developers have the `strcmp()` function for comparing strings. In JavaScript, you just use the less-
76 * than and greater-than operators:
78 * var a = "a";
79 * var b = "b";
80 * if (a < b) // true
81 * print(a + " is less than " + b);
83 * print(a + " is greater than " + b);
85 * print(a + " and " + b + " are equal.");
87 * A similar result can be achieved using the `localeCompare` method inherited by `String` instances.
89 * <div class="notice">
90 * Documentation for this class comes from <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">MDN</a>
91 * and is available under <a href="http://creativecommons.org/licenses/by-sa/2.0/">Creative Commons: Attribution-Sharealike license</a>.
95 <span id='String-method-constructor'>/**
96 </span> * @method constructor
97 * Creates new String object.
98 * @param {Object} value The value to wrap into String object.
103 <span id='String-method-fromCharCode'>/**
104 </span> * @method fromCharCode
105 * Returns a string created by using the specified sequence of Unicode values.
107 * This method returns a string and not a `String` object.
109 * Because `fromCharCode` is a static method of `String`, you always use it as `String.fromCharCode()`,
110 * rather than as a method of a `String` object you created.
112 * Although most common Unicode values can be represented in a fixed width system/with one number (as
113 * expected early on during JavaScript standardization) and `fromCharCode()` can be used to return a
114 * single character for the most common values (i.e., UCS-2 values which are the subset of UTF-16 with
115 * the most common characters), in order to deal with ALL legal Unicode values, `fromCharCode()` alone
116 * is inadequate. Since the higher code point characters use two (lower value) "surrogate" numbers to
117 * form a single character, `fromCharCode()` can be used to return such a pair and thus adequately
118 * represent these higher valued characters.
120 * Be aware, therefore, that the following utility function to grab the accurate character even for
121 * higher value code points, may be returning a value which is rendered as a single character, but
122 * which has a string count of two (though usually the count will be one).
124 * // String.fromCharCode() alone cannot get the character at such a high code point
125 * // The following, on the other hand, can return a 4-byte character as well as the
126 * // usual 2-byte ones (i.e., it can return a single character which actually has
127 * // a string length of 2 instead of 1!)
128 * alert(fixedFromCharCode(0x2F804)); // or 194564 in decimal
130 * function fixedFromCharCode (codePt) {
131 * if (codePt > 0xFFFF) {
133 * return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 +
134 * (codePt & 0x3FF));
137 * return String.fromCharCode(codePt);
141 * The following example returns the string "ABC".
143 * String.fromCharCode(65,66,67)
145 * @param {Number} num1, ..., numN A sequence of numbers that are Unicode values.
146 * @return {String} String containing characters from encoding.
151 <span id='String-property-length'>/**
152 </span> * @property {Number} length
153 * Reflects the length of the string.
155 * This property returns the number of code units in the string. UTF-16, the string format used by JavaScript, uses a single 16-bit
156 * code unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it's
157 * possible for the value returned by `length` to not match the actual number of characters in the string.
159 * For an empty string, `length` is 0.
161 * var x = "Netscape";
162 * var empty = "";
164 * console.log("Netspace is " + x.length + " code units long");
165 * console.log("The empty string is has a length of " + empty.length); // should be 0
170 <span id='String-method-charAt'>/**
171 </span> * @method charAt
172 * Returns the character at the specified index.
174 * Characters in a string are indexed from left to right. The index of the first character is 0, and
175 * the index of the last character in a string called `stringName` is `stringName.length - 1`. If the
176 * index you supply is out of range, JavaScript returns an empty string.
178 * The following example displays characters at different locations in the string "Brave new world":
180 * var anyString="Brave new world";
182 * document.writeln("The character at index 0 is '" + anyString.charAt(0) + "'");
183 * document.writeln("The character at index 1 is '" + anyString.charAt(1) + "'");
184 * document.writeln("The character at index 2 is '" + anyString.charAt(2) + "'");
185 * document.writeln("The character at index 3 is '" + anyString.charAt(3) + "'");
186 * document.writeln("The character at index 4 is '" + anyString.charAt(4) + "'");
187 * document.writeln("The character at index 999 is '" + anyString.charAt(999) + "'");
189 * These lines display the following:
191 * The character at index 0 is 'B'
192 * The character at index 1 is 'r'
193 * The character at index 2 is 'a'
194 * The character at index 3 is 'v'
195 * The character at index 4 is 'e'
196 * The character at index 999 is ''
198 * The following provides a means of ensuring that going through a string loop always provides a whole
199 * character, even if the string contains characters that are not in the Basic Multi-lingual Plane.
201 * var str = 'A\uD87E\uDC04Z'; // We could also use a non-BMP character directly
202 * for (var i=0, chr; i < str.length; i++) {
203 * if ((chr = getWholeChar(str, i)) === false) {continue;} // Adapt this line at the top of
204 * each loop, passing in the whole string and the current iteration and returning a variable to
205 * represent the individual character
209 * function getWholeChar (str, i) {
210 * var code = str.charCodeAt(i);
213 * return ''; // Position not found
215 * if (code < 0xD800 || code > 0xDFFF) {
216 * return str.charAt(i);
218 * if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F
219 * to treat high private surrogates as single characters)
220 * if (str.length <= (i+1)) {
221 * throw 'High surrogate without following low surrogate';
223 * var next = str.charCodeAt(i+1);
224 * if (0xDC00 > next || next > 0xDFFF) {
225 * throw 'High surrogate without following low surrogate';
227 * return str.charAt(i)+str.charAt(i+1);
229 * // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
231 * throw 'Low surrogate without preceding high surrogate';
233 * var prev = str.charCodeAt(i-1);
234 * if (0xD800 > prev || prev > 0xDBFF) { // (could change last hex to 0xDB7F to treat high private
235 * surrogates as single characters)
236 * throw 'Low surrogate without preceding high surrogate';
238 * return false; // We can pass over low surrogates now as the second component in a pair which we
239 * have already processed
242 * While the second example may be more frequently useful for those wishing to support non-BMP
243 * characters (since the above does not require the caller to know where any non-BMP character might
244 * appear), in the event that one _does_ wish, in choosing a character by index, to treat the surrogate
245 * pairs within a string as the single characters they represent, one can use the following:
247 * function fixedCharAt (str, idx) {
250 * var end = str.length;
252 * var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
253 * while ((surrogatePairs.exec(str)) != null) {
254 * var li = surrogatePairs.lastIndex;
255 * if (li - 2 < idx) {
263 * if (idx >= end || idx < 0) {
267 * ret += str.charAt(idx);
269 * if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx+1))) {
270 * ret += str.charAt(idx+1); // Go one further, since one of the "characters" is part of a
276 * @param {Number} index An integer between 0 and 1 less than the length of the string.
277 * @return {String} Individual character from string.
280 <span id='String-method-charCodeAt'>/**
281 </span> * @method charCodeAt
282 * Returns a number indicating the Unicode value of the character at the given index.
284 * Unicode code points range from 0 to 1,114,111. The first 128 Unicode code points are a direct match
285 * of the ASCII character encoding.
287 * Note that `charCodeAt` will always return a value that is less than 65,536. This is because the
288 * higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters which
289 * are used to comprise the real character. Because of this, in order to examine or reproduce the full
290 * character for individual characters of value 65,536 and above, for such characters, it is necessary
291 * to retrieve not only `charCodeAt(i)`, but also `charCodeAt(i+1)` (as if examining/reproducing a
292 * string with two letters). See example 2 and 3 below.
294 * `charCodeAt` returns `NaN` if the given index is not greater than 0 or is greater than the length of
297 * Backward Compatibility with JavaScript 1.2
299 * The `charCodeAt` method returns a number indicating the ISO-Latin-1 codeset value of the character
300 * at the given index. The ISO-Latin-1 codeset ranges from 0 to 255. The first 0 to 127 are a direct
301 * match of the ASCII character set.
303 * Example 1: Using `charCodeAt`
305 * The following example returns 65, the Unicode value for A.
307 * "ABC".charCodeAt(0) // returns 65
309 * Example 2: Fixing `charCodeAt` to handle non-Basic-Multilingual-Plane characters if their presence
310 * earlier in the string is unknown
312 * This version might be used in for loops and the like when it is unknown whether non-BMP characters
313 * exist before the specified index position.
315 * function fixedCharCodeAt (str, idx) {
316 * // ex. fixedCharCodeAt ('\uD800\uDC00', 0); // 65536
317 * // ex. fixedCharCodeAt ('\uD800\uDC00', 1); // 65536
319 * var code = str.charCodeAt(idx);
321 * if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
323 * low = str.charCodeAt(idx+1);
325 * throw 'High surrogate not followed by low surrogate in fixedCharCodeAt()';
327 * return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
329 * if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
330 * // We return false to allow loops to skip this iteration since should have already handled
331 * high surrogate above in the previous iteration
337 * Example 3: Fixing `charCodeAt` to handle non-Basic-Multilingual-Plane characters if their presence
338 * earlier in the string is known
340 * function knownCharCodeAt (str, idx) {
345 * var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
346 * while ((surrogatePairs.exec(str)) != null) {
347 * var li = surrogatePairs.lastIndex;
348 * if (li - 2 < idx) {
356 * if (idx >= end || idx < 0) {
360 * code = str.charCodeAt(idx);
363 * if (0xD800 <= code && code <= 0xDBFF) {
365 * low = str.charCodeAt(idx+1); // Go one further, since one of the "characters" is part of
367 * return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
372 * @param {Number} index An integer greater than 0 and less than the length of the string; if it is
373 * not a number, it defaults to 0.
374 * @return {Number} Value between 0 and 65535.
377 <span id='String-method-concat'>/**
378 </span> * @method concat
379 * Combines the text of two strings and returns a new string.
381 * `concat` combines the text from one or more strings and returns a new string. Changes to the text in
382 * one string do not affect the other string.
384 * The following example combines strings into a new string.
386 * var hello = "Hello, ";
387 * console.log(hello.concat("Kevin", " have a nice day.")); // Hello, Kevin have a nice day.
389 * @param {String} string2...stringN
390 * @return {String} Result of both strings.
393 <span id='String-method-indexOf'>/**
394 </span> * @method indexOf
395 * Returns the index within the calling `String` object of the first occurrence of the specified value,
396 * or -1 if not found.
398 * Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character
399 * of a string called `stringName` is `stringName.length - 1`.
401 * "Blue Whale".indexOf("Blue") // returns 0
402 * "Blue Whale".indexOf("Blute") // returns -1
403 * "Blue Whale".indexOf("Whale",0) // returns 5
404 * "Blue Whale".indexOf("Whale",5) // returns 5
405 * "Blue Whale".indexOf("",9) // returns 9
406 * "Blue Whale".indexOf("",10) // returns 10
407 * "Blue Whale".indexOf("",11) // returns 10
409 * The `indexOf` method is case sensitive. For example, the following expression returns -1:
411 * "Blue Whale".indexOf("blue")
413 * Note that '0' doesn't evaluate to true and '-1' doesn't evaluate to false. Therefore, when checking if a specific string exists
414 * within another string the correct way to check would be:
416 * "Blue Whale".indexOf("Blue") != -1 // true
417 * "Blue Whale".indexOf("Bloe") != -1 // false
419 * The following example uses indexOf and lastIndexOf to locate values in the string "Brave new world".
421 * var anyString="Brave new world"
423 * document.write("<P>The index of the first w from the beginning is " + anyString.indexOf("w")) // Displays 8
424 * document.write("<P>The index of the first w from the end is " + anyString.lastIndexOf("w")) // Displays 10
425 * document.write("<P>The index of 'new' from the beginning is " + anyString.indexOf("new")) // Displays 6
426 * document.write("<P>The index of 'new' from the end is " + anyString.lastIndexOf("new")) // Displays 6
428 * The following example defines two string variables. The variables contain the same string except that the second string contains
429 * uppercase letters. The first `writeln` method displays 19. But because the `indexOf` method is case sensitive, the string
430 * "cheddar" is not found in `myCapString`, so the second `writeln` method displays -1.
432 * myString="brie, pepper jack, cheddar"
433 * myCapString="Brie, Pepper Jack, Cheddar"
434 * document.writeln('myString.indexOf("cheddar") is ' + myString.indexOf("cheddar"))
435 * document.writeln('<P>myCapString.indexOf("cheddar") is ' + myCapString.indexOf("cheddar"))
437 * The following example sets count to the number of occurrences of the letter x in the string str:
440 * pos = str.indexOf("x");
441 * while ( pos != -1 ) {
443 * pos = str.indexOf("x",pos+1);
446 * @param {String} searchValue A string representing the value to search for.
447 * @param {Number} fromIndex The location within the calling string to start the search from. It can be any integer between 0 and
448 * the length of the string. The default value is 0.
449 * @return {Number} Position of specified value or -1 if not found.
452 <span id='String-method-lastIndexOf'>/**
453 </span> * @method lastIndexOf
454 * Returns the index within the calling String object of the last occurrence of
455 * the specified value, or -1 if not found. The calling string is searched
456 * backward, starting at fromIndex.
458 * Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character
459 * is `stringName.length - 1`.
461 * "canal".lastIndexOf("a") // returns 3
462 * "canal".lastIndexOf("a",2) // returns 1
463 * "canal".lastIndexOf("a",0) // returns -1
464 * "canal".lastIndexOf("x") // returns -1
466 * The `lastIndexOf` method is case sensitive. For example, the following expression returns -1:
468 * "Blue Whale, Killer Whale".lastIndexOf("blue")
470 * The following example uses `indexOf` and `lastIndexOf` to locate values in the string "`Brave new world`".
472 * var anyString="Brave new world"
475 * document.write("<P>The index of the first w from the beginning is " +
476 * anyString.indexOf("w"))
478 * document.write("<P>The index of the first w from the end is " +
479 * anyString.lastIndexOf("w"))
481 * document.write("<P>The index of 'new' from the beginning is " +
482 * anyString.indexOf("new"))
484 * document.write("<P>The index of 'new' from the end is " +
485 * anyString.lastIndexOf("new"))
487 * @param {String} searchValue A string representing the value to search for.
488 * @param {Number} fromIndex The location within the calling string to start the search from, indexed from left to right. It can
489 * be any integer between 0 and the length of the string. The default value is the length of the string.
493 <span id='String-method-localeCompare'>/**
494 </span> * @method localeCompare
495 * Returns a number indicating whether a reference string comes before or after or is the same as the
496 * given string in sort order.
498 * Returns a number indicating whether a reference string comes before or after or is the same as the
499 * given string in sort order. Returns -1 if the string occurs earlier in a sort than `compareString`,
500 * returns 1 if the string occurs afterwards in such a sort, and returns 0 if they occur at the same
503 * The following example demonstrates the different potential results for a string occurring before,
504 * after, or at the same level as another:
506 * alert('a'.localeCompare('b')); // -1
507 * alert('b'.localeCompare('a')); // 1
508 * alert('b'.localeCompare('b')); // 0
510 * @param {String} compareString The string against which the referring string is comparing.
511 * @return {Number} Returns -1 if the string occurs earlier in a sort than
512 * compareString, returns 1 if the string occurs afterwards in such a sort, and
513 * returns 0 if they occur at the same level.
516 <span id='String-method-match'>/**
517 </span> * @method match
518 * Used to match a regular expression against a string.
520 * If the regular expression does not include the `g` flag, returns the same result as `regexp.exec(string)`.
522 * If the regular expression includes the `g` flag, the method returns an Array containing all matches. If there were no matches,
523 * the method returns `null`.
525 * The returned {@link Array} has an extra `input` property, which contains the regexp that generated it as a result. In addition,
526 * it has an `index` property, which represents the zero-based index of the match in the string.
528 * In the following example, `match` is used to find "Chapter" followed by 1 or more numeric characters followed by a decimal point
529 * and numeric character 0 or more times. The regular expression includes the `i` flag so that case will be ignored.
531 * str = "For more information, see Chapter 3.4.5.1";
532 * re = /(chapter \d+(\.\d)*)/i;
533 * found = str.match(re);
534 * document.write(found);
536 * This returns the array containing Chapter 3.4.5.1,Chapter 3.4.5.1,.1
538 * "`Chapter 3.4.5.1`" is the first match and the first value remembered from `(Chapter \d+(\.\d)*)`.
540 * "`.1`" is the second value remembered from `(\.\d)`.
542 * The following example demonstrates the use of the global and ignore case flags with `match`. All letters A through E and a
543 * through e are returned, each its own element in the array
545 * var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
546 * var regexp = /[A-E]/gi;
547 * var matches_array = str.match(regexp);
548 * document.write(matches_array);
550 * `matches_array` now equals `['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']`.
552 * @param {RegExp} regexp A {@link RegExp} object. If a non-RegExp object `obj` is passed, it is
553 * implicitly converted to a RegExp by using `new RegExp(obj)`.
554 * @return {Array} Contains results of the match (if any).
557 <span id='String-method-replace'>/**
558 </span> * @method replace
559 * Used to find a match between a regular expression and a string, and to replace the matched substring
560 * with a new substring.
562 * This method does not change the `String` object it is called on. It simply returns a new string.
564 * To perform a global search and replace, either include the `g` flag in the regular expression or if
565 * the first parameter is a string, include `g` in the flags parameter.
567 * The replacement string can include the following special replacement patterns:
569 * | Pattern | Inserts
570 * |:--------------|:--------------------------------------------------------------------------------------
571 * | `$$` | Inserts a `$`.
572 * | `$&` | Inserts the matched substring.
573 * | `$`` | Inserts the portion of the string that precedes the matched substring.
574 * | `$'` | Inserts the portion of the string that follows the matched substring.
575 * | `$n` or `$nn` | Where `n` or `nn` are decimal digits, inserts the _n_th parenthesized submatch string, provided the first
576 * | | argument was a `RegExp` object.
578 * You can specify a function as the second parameter. In this case, the function will be invoked after the match has been
579 * performed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special
580 * replacement patterns do not apply in this case.) Note that the function will be invoked multiple times for each full match to be
581 * replaced if the regular expression in the first parameter is global.
583 * The arguments to the function are as follows:
585 * | Possible Name | Supplied Value
586 * |:--------------|:--------------------------------------------------------------------------------------
587 * | `str` | The matched substring. (Corresponds to `$&` above.)
588 * | `p1, p2, ...` | The _n_th parenthesized submatch string, provided the first argument to replace was a `RegExp` object.
589 * | | (Correspond to $1, $2, etc. above.)
590 * | `offset` | The offset of the matched substring within the total string being examined. (For example, if the total string
591 * | | was "`abcd`", and the matched substring was "`bc`", then this argument will be 1.)
592 * | `s` | The total string being examined.
594 * (The exact number of arguments will depend on whether the first argument was a `RegExp` object and, if so, how many parenthesized
595 * submatches it specifies.)
597 * The following example will set `newString` to "`XXzzzz - XX , zzzz`":
599 * function replacer(str, p1, p2, offset, s)
601 * return str + " - " + p1 + " , " + p2;
603 * var newString = "XXzzzz".replace(/(X*)(z*)/, replacer);
605 * In the following example, the regular expression includes the global and ignore case flags which permits replace to replace each
606 * occurrence of 'apples' in the string with 'oranges'.
608 * var re = /apples/gi;
609 * var str = "Apples are round, and apples are juicy.";
610 * var newstr = str.replace(re, "oranges");
613 * In this version, a string is used as the first parameter and the global and ignore case flags are specified in the flags
616 * var str = "Apples are round, and apples are juicy.";
617 * var newstr = str.replace("apples", "oranges", "gi");
620 * Both of these examples print "oranges are round, and oranges are juicy."
622 * In the following example, the regular expression is defined in replace and includes the ignore case flag.
624 * var str = "Twas the night before Xmas...";
625 * var newstr = str.replace(/xmas/i, "Christmas");
628 * This prints "Twas the night before Christmas..."
630 * The following script switches the words in the string. For the replacement text, the script uses the $1 and $2 replacement
633 * var re = /(\w+)\s(\w+)/;
634 * var str = "John Smith";
635 * var newstr = str.replace(re, "$2, $1");
638 * This prints "Smith, John".
640 * In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just
641 * before the match location. The important thing here is that additional operations are needed on the matched item before it is
642 * given back as a replacement.
644 * The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the
645 * hyphen before returning.
647 * function styleHyphenFormat(propertyName)
649 * function upperToHyphenLower(match)
651 * return '-' + match.toLowerCase();
653 * return propertyName.replace(/[A-Z]/, upperToHyphenLower);
656 * Given `styleHyphenFormat('borderTop')`, this returns 'border-top'.
658 * Because we want to further transform the _result_ of the match before the final substitution is made, we must use a function.
659 * This forces the evaluation of the match prior to the `toLowerCase()` method. If we had tried to do this using the match without a
660 * function, the `toLowerCase()` would have no effect.
662 * var newString = propertyName.replace(/[A-Z]/, '-' + '$&'.toLowerCase()); // won't work
664 * This is because `'$&'.toLowerCase()` would be evaluated first as a string literal (resulting in the same `'$&'`) before using the
665 * characters as a pattern.
667 * The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number
668 * ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function
669 * returns 100C. If the number is 0F, the function returns -17.77777777777778C.
671 * The regular expression `test` checks for any number that ends with F. The number of Fahrenheit degree is accessible to the
672 * function through its second parameter, `p1`. The function sets the Celsius number based on the Fahrenheit degree passed in a
673 * string to the `f2c` function. `f2c` then returns the Celsius number. This function approximates Perl's `s///e` flag.
677 * function convert(str, p1, offset, s)
679 * return ((p1-32) * 5/9) + "C";
682 * var test = /(\d+(?:\.\d*)?)F\b/g;
683 * return s.replace(test, convert);
686 * @param {RegExp} regexp A RegExp object. The match is replaced by the return value of parameter #2.
687 * @param {String} substr A String that is to be replaced by `newSubStr`.
688 * @param {String} newSubStr The String that replaces the substring received from parameter #1. A
689 * number of special replacement patterns are supported; see the "Specifying a string as a parameter"
691 * @param {Function} function A function to be invoked to create the new substring (to put in place
692 * of the substring received from parameter #1). The arguments supplied to this function are described
693 * in the "Specifying a function as a parameter" section below.
694 * @return {String} String of matched replaced items.
697 <span id='String-method-search'>/**
698 </span> * @method search
699 * Executes the search for a match between a regular expression and a specified string.
701 * If successful, search returns the index of the regular expression inside the string. Otherwise, it
704 * When you want to know whether a pattern is found in a string use search (similar to the regular
705 * expression `test` method); for more information (but slower execution) use `match` (similar to the
706 * regular expression `exec` method).
708 * The following example prints a message which depends on the success of the test.
710 * function testinput(re, str){
711 * if (str.search(re) != -1)
712 * midstring = " contains ";
714 * midstring = " does not contain ";
715 * document.write (str + midstring + re);
718 * @param {RegExp} regexp A regular expression object. If a non-RegExp object obj is passed, it is
719 * implicitly converted to a RegExp by using `new RegExp(obj)`.
720 * @return {Number} If successful, search returns the index of the regular
721 * expression inside the string. Otherwise, it returns -1.
724 <span id='String-method-slice'>/**
725 </span> * @method slice
726 * Extracts a section of a string and returns a new string.
728 * `slice` extracts the text from one string and returns a new string. Changes to the text in one
729 * string do not affect the other string.
731 * `slice` extracts up to but not including `endSlice`. `string.slice(1,4)` extracts the second
732 * character through the fourth character (characters indexed 1, 2, and 3).
734 * As a negative index, `endSlice` indicates an offset from the end of the string. `string.slice(2,-1)`
735 * extracts the third character through the second to last character in the string.
737 * The following example uses slice to create a new string.
739 * // assumes a print function is defined
740 * var str1 = "The morning is upon us.";
741 * var str2 = str1.slice(4, -2);
748 * @param {Number} beginSlice The zero-based index at which to begin extraction.
749 * @param {Number} endSlice The zero-based index at which to end extraction. If omitted, `slice`
750 * extracts to the end of the string.
751 * @return {String} All characters from specified start up to (but excluding)
755 <span id='String-method-split'>/**
756 </span> * @method split
757 * Splits a `String` object into an array of strings by separating the string into substrings.
759 * The `split` method returns the new array.
761 * When found, `separator` is removed from the string and the substrings are returned in an array. If
762 * `separator` is omitted, the array contains one element consisting of the entire string.
764 * If `separator` is a regular expression that contains capturing parentheses, then each time separator
765 * is matched the results (including any undefined results) of the capturing parentheses are spliced
766 * into the output array. However, not all browsers support this capability.
768 * Note: When the string is empty, `split` returns an array containing one empty string, rather than an
771 * The following example defines a function that splits a string into an array of strings using the
772 * specified separator. After splitting the string, the function displays messages indicating the
773 * original string (before the split), the separator used, the number of elements in the array, and the
774 * individual array elements.
776 * function splitString(stringToSplit,separator)
778 * var arrayOfStrings = stringToSplit.split(separator);
779 * print('The original string is: "' + stringToSplit + '"');
780 * print('The separator is: "' + separator + '"');
781 * print("The array has " + arrayOfStrings.length + " elements: ");
783 * for (var i=0; i < arrayOfStrings.length; i++)
784 * print(arrayOfStrings[i] + " / ");
787 * var tempestString = "Oh brave new world that has such people in it.";
788 * var monthString = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
790 * var space = " ";
791 * var comma = ",";
793 * splitString(tempestString, space);
794 * splitString(tempestString);
795 * splitString(monthString, comma);
797 * This example produces the following output:
799 * The original string is: "Oh brave new world that has such people in it."
800 * The separator is: " "
801 * The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. /
803 * The original string is: "Oh brave new world that has such people in it."
804 * The separator is: "undefined"
805 * The array has 1 elements: Oh brave new world that has such people in it. /
807 * The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
808 * The separator is: ","
809 * The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec /
811 * In the following example, `split` looks for 0 or more spaces followed by a semicolon followed by 0
812 * or more spaces and, when found, removes the spaces from the string. nameList is the array returned
813 * as a result of split.
815 * var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";
817 * var re = /\s*;\s*\/;
818 * var nameList = names.split(re);
821 * This prints two lines; the first line prints the original string, and the second line prints the
824 * Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
825 * Harry Trump,Fred Barney,Helen Rigby,Bill Abel,Chris Hand
827 * In the following example, split looks for 0 or more spaces in a string and returns the first 3
828 * splits that it finds.
830 * var myString = "Hello World. How are you doing?";
831 * var splits = myString.split(" ", 3);
834 * This script displays the following:
838 * If `separator` contains capturing parentheses, matched results are returned in the array.
840 * var myString = "Hello 1 word. Sentence number 2.";
841 * var splits = myString.split(/(\d)/);
844 * This script displays the following:
846 * Hello ,1, word. Sentence number ,2, .
848 * @param {String} seperator Specifies the character to use for separating the string. The separator is treated as a string or a
849 * regular expression. If separator is omitted, the array returned contains one element consisting of the entire string.
850 * @param {Number} limit Integer specifying a limit on the number of splits to be found. The split method still splits on every
851 * match of separator, but it truncates the returned array to at most limit elements.
852 * @return {Array} Substrings are returned in an array.
855 <span id='String-method-substr'>/**
856 </span> * @method substr
857 * Returns the characters in a string beginning at the specified location through the specified number
860 * `start` is a character index. The index of the first character is 0, and the index of the last
861 * character is 1 less than the length of the string. `substr` begins extracting characters at start
862 * and collects length characters (unless it reaches the end of the string first, in which case it will
865 * If `start` is positive and is greater than or equal to the length of the string, `substr` returns an
868 * If `start` is negative, `substr` uses it as a character index from the end of the string. If start
869 * is negative and abs(start) is larger than the length of the string, `substr` uses 0 as the start
870 * index. Note: the described handling of negative values of the start argument is not supported by
873 * If length is 0 or negative, `substr` returns an empty string. If length is omitted, `substr`
874 * extracts characters to the end of the string.
876 * Consider the following script:
878 * // assumes a print function is defined
879 * var str = "abcdefghij";
880 * print("(1,2): " + str.substr(1,2));
881 * print("(-3,2): " + str.substr(-3,2));
882 * print("(-3): " + str.substr(-3));
883 * print("(1): " + str.substr(1));
884 * print("(-20, 2): " + str.substr(-20,2));
885 * print("(20, 2): " + str.substr(20,2));
887 * This script displays:
896 * @param {Number} start Location at which to begin extracting characters.
897 * @param {Number} length The number of characters to extract.
898 * @return {String} Modified string.
901 <span id='String-method-substring'>/**
902 </span> * @method substring
903 * Returns the characters in a string between two indexes into the string.
905 * substring extracts characters from indexA up to but not including indexB. In particular:
906 * * If `indexA` equals `indexB`, `substring` returns an empty string.
907 * * If `indexB` is omitted, substring extracts characters to the end of the string.
908 * * If either argument is less than 0 or is `NaN`, it is treated as if it were 0.
909 * * If either argument is greater than `stringName.length`, it is treated as if it were
910 * `stringName.length`.
912 * If `indexA` is larger than `indexB`, then the effect of substring is as if the two arguments were
913 * swapped; for example, `str.substring(1, 0) == str.substring(0, 1)`.
915 * The following example uses substring to display characters from the string "Sencha":
917 * // assumes a print function is defined
918 * var anyString = "Sencha";
920 * // Displays "Sen"
921 * print(anyString.substring(0,3));
922 * print(anyString.substring(3,0));
924 * // Displays "cha"
925 * print(anyString.substring(3,6));
926 * print(anyString.substring(6,3));
928 * // Displays "Sencha"
929 * print(anyString.substring(0,6));
930 * print(anyString.substring(0,10));
932 * The following example replaces a substring within a string. It will replace both individual
933 * characters and `substrings`. The function call at the end of the example changes the string "Brave
934 * New World" into "Brave New Web".
936 * function replaceString(oldS, newS, fullS) {
937 * // Replaces oldS with newS in the string fullS
938 * for (var i = 0; i < fullS.length; i++) {
939 * if (fullS.substring(i, i + oldS.length) == oldS) {
940 * fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length,
947 * replaceString("World", "Web", "Brave New World");
949 * @param {Number} indexA An integer between 0 and one less than the length of the string.
950 * @param {Number} indexB (optional) An integer between 0 and the length of the string.
951 * @return {String} Returns the characters in a string between two indexes into the string.
954 <span id='String-method-toLocaleLowerCase'>/**
955 </span> * @method toLocaleLowerCase
956 * The characters within a string are converted to lower case while respecting the current locale. For
957 * most languages, this will return the same as `toLowerCase`.
959 * The `toLocaleLowerCase` method returns the value of the string converted to lower case according to
960 * any locale-specific case mappings. `toLocaleLowerCase` does not affect the value of the string
961 * itself. In most cases, this will produce the same result as `toLowerCase()`, but for some locales,
962 * such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may
963 * be a different result.
965 * The following example displays the string "sencha":
967 * var upperText="sencha";
968 * document.write(upperText.toLocaleLowerCase());
970 * @return {String} Returns value of the string in lowercase.
973 <span id='String-method-toLocaleUpperCase'>/**
974 </span> * @method toLocaleUpperCase
975 * The characters within a string are converted to upper case while respecting the current locale. For
976 * most languages, this will return the same as `toUpperCase`.
978 * The `toLocaleUpperCase` method returns the value of the string converted to upper case according to
979 * any locale-specific case mappings. `toLocaleUpperCase` does not affect the value of the string
980 * itself. In most cases, this will produce the same result as `toUpperCase()`, but for some locales,
981 * such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may
982 * be a different result.
984 * The following example displays the string "SENCHA":
986 * var lowerText="sencha";
987 * document.write(lowerText.toLocaleUpperCase());
989 * @return {String} Returns value of the string in uppercase.
992 <span id='String-method-toLowerCase'>/**
993 </span> * @method toLowerCase
994 * Returns the calling string value converted to lower case.
996 * The `toLowerCase` method returns the value of the string converted to lowercase. `toLowerCase` does
997 * not affect the value of the string itself.
999 * The following example displays the lowercase string "sencha":
1001 * var upperText="SENCHA";
1002 * document.write(upperText.toLowerCase());
1004 * @return {String} Returns value of the string in lowercase.
1007 <span id='String-method-toString'>/**
1008 </span> * @method toString
1009 * Returns a string representing the specified object. Overrides the `Object.toString` method.
1011 * The `String` object overrides the `toString` method of the `Object` object; it does not inherit
1012 * `Object.toString`. For `String` objects, the `toString` method returns a string representation of
1015 * The following example displays the string value of a String object:
1017 * x = new String("Hello world");
1018 * alert(x.toString()) // Displays "Hello world"
1020 * @return {String} A string representation of the object.
1023 <span id='String-method-toUpperCase'>/**
1024 </span> * @method toUpperCase
1025 * Returns the calling string value converted to uppercase.
1027 * The `toUpperCase` method returns the value of the string converted to uppercase. `toUpperCase` does
1028 * not affect the value of the string itself.
1030 * The following example displays the string "SENCHA":
1032 * var lowerText="sencha";
1033 * document.write(lowerText.toUpperCase());
1035 * @return {String} Returns value of the string in uppercase.
1038 <span id='String-method-valueOf'>/**
1039 </span> * @method valueOf
1040 * Returns the primitive value of the specified object. Overrides the `Object.valueOf` method.
1042 * The `valueOf` method of String returns the primitive value of a `String` object as a string data
1043 * type. This value is equivalent to `String.toString`.
1045 * This method is usually called internally by JavaScript and not explicitly in code.
1047 * x = new String("Hello world");
1048 * alert(x.valueOf()) // Displays "Hello world"
1050 * @return {String} Returns value of string.