X-Git-Url: http://git.ithinksw.org/extjs.git/blobdiff_plain/6746dc89c47ed01b165cc1152533605f97eb8e8d..f562e4c6e5fac7bcb445985b99acbea4d706e6f0:/docs/output/String.js diff --git a/docs/output/String.js b/docs/output/String.js new file mode 100644 index 00000000..81101986 --- /dev/null +++ b/docs/output/String.js @@ -0,0 +1 @@ +Ext.data.JsonP.String({"tagname":"class","html":"
Files
String
is a global object that may be used to construct String instances.
String objects may be created by calling the constructor new String()
. The String
object wraps\nJavaScript's string primitive data type with the methods described below. The global function\nString()
can also be called without new in front to create a primitive string. String literals in\nJavaScript are primitive strings.
Because JavaScript automatically converts between string primitives and String objects, you can call\nany of the methods of the String
object on a string primitive. JavaScript automatically converts the\nstring primitive to a temporary String
object, calls the method, then discards the temporary String\nobject. For example, you can use the String.length
property on a string primitive created from a\nstring literal:
s_obj = new String(s_prim = s_also_prim = \"foo\");\n\ns_obj.length; // 3\ns_prim.length; // 3\ns_also_prim.length; // 3\n'foo'.length; // 3\n\"foo\".length; // 3\n
\n\n(A string literal is denoted with single or double quotation marks.)
\n\nString objects can be converted to primitive strings with the valueOf
method.
String primitives and String objects give different results when evaluated as JavaScript. Primitives\nare treated as source code; String objects are treated as a character sequence object. For example:
\n\ns1 = \"2 + 2\"; // creates a string primitive\ns2 = new String(\"2 + 2\"); // creates a String object\neval(s1); // returns the number 4\neval(s2); // returns the string \"2 + 2\"\neval(s2.valueOf()); // returns the number 4\n
\n\nThere are two ways to access an individual character in a string. The first is the charAt
method:
return 'cat'.charAt(1); // returns \"a\"\n
\n\nThe other way is to treat the string as an array, where each index corresponds to an individual\ncharacter:
\n\nreturn 'cat'[1]; // returns \"a\"\n
\n\nThe second way (treating the string as an array) is not part of ECMAScript 3. It is a JavaScript and\nECMAScript 5 feature.
\n\nIn both cases, attempting to set an individual character won't work. Trying to set a character\nthrough charAt
results in an error, while trying to set a character via indexing does not throw an\nerror, but the string itself is unchanged.
C developers have the strcmp()
function for comparing strings. In JavaScript, you just use the less-\nthan and greater-than operators:
var a = \"a\";\nvar b = \"b\";\nif (a < b) // true\n print(a + \" is less than \" + b);\nelse if (a > b)\n print(a + \" is greater than \" + b);\nelse\n print(a + \" and \" + b + \" are equal.\");\n
\n\nA similar result can be achieved using the localeCompare
method inherited by String
instances.
Reflects the length of the string.
\n\nThis property returns the number of code units in the string. UTF-16, the string format used by JavaScript, uses a single 16-bit\ncode unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it's\npossible for the value returned by length
to not match the actual number of characters in the string.
For an empty string, length
is 0.
var x = \"Netscape\";\nvar empty = \"\";\n\nconsole.log(\"Netspace is \" + x.length + \" code units long\");\nconsole.log(\"The empty string is has a length of \" + empty.length); // should be 0\n
\nReturns the character at the specified index.
\n\nCharacters in a string are indexed from left to right. The index of the first character is 0, and\nthe index of the last character in a string called stringName
is stringName.length - 1
. If the\nindex you supply is out of range, JavaScript returns an empty string.
The following example displays characters at different locations in the string \"Brave new world\":
\n\nvar anyString=\"Brave new world\";\n\ndocument.writeln(\"The character at index 0 is '\" + anyString.charAt(0) + \"'\");\ndocument.writeln(\"The character at index 1 is '\" + anyString.charAt(1) + \"'\");\ndocument.writeln(\"The character at index 2 is '\" + anyString.charAt(2) + \"'\");\ndocument.writeln(\"The character at index 3 is '\" + anyString.charAt(3) + \"'\");\ndocument.writeln(\"The character at index 4 is '\" + anyString.charAt(4) + \"'\");\ndocument.writeln(\"The character at index 999 is '\" + anyString.charAt(999) + \"'\");\n
\n\nThese lines display the following:
\n\nThe character at index 0 is 'B'\nThe character at index 1 is 'r'\nThe character at index 2 is 'a'\nThe character at index 3 is 'v'\nThe character at index 4 is 'e'\nThe character at index 999 is ''\n
\n\nThe following provides a means of ensuring that going through a string loop always provides a whole\ncharacter, even if the string contains characters that are not in the Basic Multi-lingual Plane.
\n\nvar str = 'A\\uD87E\\uDC04Z'; // We could also use a non-BMP character directly\nfor (var i=0, chr; i < str.length; i++) {\n if ((chr = getWholeChar(str, i)) === false) {continue;} // Adapt this line at the top of\n
\n\neach loop, passing in the whole string and the current iteration and returning a variable to\nrepresent the individual character
\n\n alert(chr);\n}\n\nfunction getWholeChar (str, i) {\n var code = str.charCodeAt(i);\n\n if (isNaN(code)) {\n return ''; // Position not found\n }\n if (code < 0xD800 || code > 0xDFFF) {\n return str.charAt(i);\n }\n if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F\n
\n\nto treat high private surrogates as single characters)
\n\n if (str.length <= (i+1)) {\n throw 'High surrogate without following low surrogate';\n }\n var next = str.charCodeAt(i+1);\n if (0xDC00 > next || next > 0xDFFF) {\n throw 'High surrogate without following low surrogate';\n }\n return str.charAt(i)+str.charAt(i+1);\n}\n// Low surrogate (0xDC00 <= code && code <= 0xDFFF)\nif (i === 0) {\n throw 'Low surrogate without preceding high surrogate';\n}\nvar prev = str.charCodeAt(i-1);\nif (0xD800 > prev || prev > 0xDBFF) { // (could change last hex to 0xDB7F to treat high private\n
\n\nsurrogates as single characters)
\n\n throw 'Low surrogate without preceding high surrogate';\n}\nreturn false; // We can pass over low surrogates now as the second component in a pair which we\n
\n\nhave already processed\n}
\n\nWhile the second example may be more frequently useful for those wishing to support non-BMP\ncharacters (since the above does not require the caller to know where any non-BMP character might\nappear), in the event that one does wish, in choosing a character by index, to treat the surrogate\npairs within a string as the single characters they represent, one can use the following:
\n\nfunction fixedCharAt (str, idx) {\n var ret = '';\n str += '';\n var end = str.length;\n\n var surrogatePairs = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g;\n while ((surrogatePairs.exec(str)) != null) {\n var li = surrogatePairs.lastIndex;\n if (li - 2 < idx) {\n idx++;\n }\n else {\n break;\n }\n}\n\nif (idx >= end || idx < 0) {\n return '';\n}\n\nret += str.charAt(idx);\n\nif (/[\\uD800-\\uDBFF]/.test(ret) && /[\\uDC00-\\uDFFF]/.test(str.charAt(idx+1))) {\n ret += str.charAt(idx+1); // Go one further, since one of the \"characters\" is part of a\n
\n\nsurrogate pair
\n\n}\nreturn ret;\n}\n
\nAn integer between 0 and 1 less than the length of the string.
\nIndividual character from string.
\nReturns a number indicating the Unicode value of the character at the given index.
\n\nUnicode code points range from 0 to 1,114,111. The first 128 Unicode code points are a direct match\nof the ASCII character encoding.
\n\nNote that charCodeAt
will always return a value that is less than 65,536. This is because the\nhigher code points are represented by a pair of (lower valued) \"surrogate\" pseudo-characters which\nare used to comprise the real character. Because of this, in order to examine or reproduce the full\ncharacter for individual characters of value 65,536 and above, for such characters, it is necessary\nto retrieve not only charCodeAt(i)
, but also charCodeAt(i+1)
(as if examining/reproducing a\nstring with two letters). See example 2 and 3 below.
charCodeAt
returns NaN
if the given index is not greater than 0 or is greater than the length of\nthe string.
Backward Compatibility with JavaScript 1.2
\n\nThe charCodeAt
method returns a number indicating the ISO-Latin-1 codeset value of the character\nat the given index. The ISO-Latin-1 codeset ranges from 0 to 255. The first 0 to 127 are a direct\nmatch of the ASCII character set.
Example 1: Using charCodeAt
The following example returns 65, the Unicode value for A.
\n\n\"ABC\".charCodeAt(0) // returns 65
\n\nExample 2: Fixing charCodeAt
to handle non-Basic-Multilingual-Plane characters if their presence\nearlier in the string is unknown
This version might be used in for loops and the like when it is unknown whether non-BMP characters\nexist before the specified index position.
\n\nfunction fixedCharCodeAt (str, idx) {\n // ex. fixedCharCodeAt ('\\uD800\\uDC00', 0); // 65536\n // ex. fixedCharCodeAt ('\\uD800\\uDC00', 1); // 65536\n idx = idx || 0;\n var code = str.charCodeAt(idx);\n var hi, low;\n if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)\n hi = code;\n low = str.charCodeAt(idx+1);\n if (isNaN(low)) {\n throw 'High surrogate not followed by low surrogate in fixedCharCodeAt()';\n }\n return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;\n }\n if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate\n // We return false to allow loops to skip this iteration since should have already handled\n
\n\nhigh surrogate above in the previous iteration
\n\n return false;\n }\n return code;\n}\n
\n\nExample 3: Fixing charCodeAt
to handle non-Basic-Multilingual-Plane characters if their presence\nearlier in the string is known
function knownCharCodeAt (str, idx) {\n str += '';\n var code,\n end = str.length;\n\n var surrogatePairs = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g;\n while ((surrogatePairs.exec(str)) != null) {\n var li = surrogatePairs.lastIndex;\n if (li - 2 < idx) {\n idx++;\n }\n else {\n break;\n }\n }\n\n if (idx >= end || idx < 0) {\n return NaN;\n }\n\n code = str.charCodeAt(idx);\n\n var hi, low;\n if (0xD800 <= code && code <= 0xDBFF) {\n hi = code;\n low = str.charCodeAt(idx+1); // Go one further, since one of the \"characters\" is part of\n
\n\na surrogate pair
\n\n return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;\n }\n return code;\n}\n
\nAn integer greater than 0 and less than the length of the string; if it is\nnot a number, it defaults to 0.
\nValue between 0 and 65535.
\nCombines the text of two strings and returns a new string.
\n\nconcat
combines the text from one or more strings and returns a new string. Changes to the text in\none string do not affect the other string.
The following example combines strings into a new string.
\n\nvar hello = \"Hello, \";\nconsole.log(hello.concat(\"Kevin\", \" have a nice day.\")); // Hello, Kevin have a nice day.\n
\n...stringN
\nResult of both strings.
\nReturns a string created by using the specified sequence of Unicode values.
\n\nThis method returns a string and not a String
object.
Because fromCharCode
is a static method of String
, you always use it as String.fromCharCode()
,\nrather than as a method of a String
object you created.
Although most common Unicode values can be represented in a fixed width system/with one number (as\nexpected early on during JavaScript standardization) and fromCharCode()
can be used to return a\nsingle character for the most common values (i.e., UCS-2 values which are the subset of UTF-16 with\nthe most common characters), in order to deal with ALL legal Unicode values, fromCharCode()
alone\nis inadequate. Since the higher code point characters use two (lower value) \"surrogate\" numbers to\nform a single character, fromCharCode()
can be used to return such a pair and thus adequately\nrepresent these higher valued characters.
Be aware, therefore, that the following utility function to grab the accurate character even for\nhigher value code points, may be returning a value which is rendered as a single character, but\nwhich has a string count of two (though usually the count will be one).
\n\n// String.fromCharCode() alone cannot get the character at such a high code point\n// The following, on the other hand, can return a 4-byte character as well as the\n// usual 2-byte ones (i.e., it can return a single character which actually has\n// a string length of 2 instead of 1!)\nalert(fixedFromCharCode(0x2F804)); // or 194564 in decimal\n\nfunction fixedFromCharCode (codePt) {\n if (codePt > 0xFFFF) {\n codePt -= 0x10000;\n return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 +\n (codePt & 0x3FF));\n }\n else {\n return String.fromCharCode(codePt);\n }\n}\n
\n\nThe following example returns the string \"ABC\".
\n\nString.fromCharCode(65,66,67)\n
\n, ..., numN A sequence of numbers that are Unicode values.
\nString containing characters from encoding.
\nReturns the index within the calling String
object of the first occurrence of the specified value,\nor -1 if not found.
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\nof a string called stringName
is stringName.length - 1
.
\"Blue Whale\".indexOf(\"Blue\") // returns 0\n\"Blue Whale\".indexOf(\"Blute\") // returns -1\n\"Blue Whale\".indexOf(\"Whale\",0) // returns 5\n\"Blue Whale\".indexOf(\"Whale\",5) // returns 5\n\"Blue Whale\".indexOf(\"\",9) // returns 9\n\"Blue Whale\".indexOf(\"\",10) // returns 10\n\"Blue Whale\".indexOf(\"\",11) // returns 10\n
\n\nThe indexOf
method is case sensitive. For example, the following expression returns -1:
\"Blue Whale\".indexOf(\"blue\")\n
\n\nNote that '0' doesn't evaluate to true and '-1' doesn't evaluate to false. Therefore, when checking if a specific string exists\nwithin another string the correct way to check would be:
\n\n\"Blue Whale\".indexOf(\"Blue\") != -1 // true\n\"Blue Whale\".indexOf(\"Bloe\") != -1 // false\n
\n\nThe following example uses indexOf and lastIndexOf to locate values in the string \"Brave new world\".
\n\nvar anyString=\"Brave new world\"\n\ndocument.write(\"<P>The index of the first w from the beginning is \" + anyString.indexOf(\"w\")) // Displays 8\ndocument.write(\"<P>The index of the first w from the end is \" + anyString.lastIndexOf(\"w\")) // Displays 10\ndocument.write(\"<P>The index of 'new' from the beginning is \" + anyString.indexOf(\"new\")) // Displays 6\ndocument.write(\"<P>The index of 'new' from the end is \" + anyString.lastIndexOf(\"new\")) // Displays 6\n
\n\nThe following example defines two string variables. The variables contain the same string except that the second string contains\nuppercase letters. The first writeln
method displays 19. But because the indexOf
method is case sensitive, the string\n\"cheddar\" is not found in myCapString
, so the second writeln
method displays -1.
myString=\"brie, pepper jack, cheddar\"\nmyCapString=\"Brie, Pepper Jack, Cheddar\"\ndocument.writeln('myString.indexOf(\"cheddar\") is ' + myString.indexOf(\"cheddar\"))\ndocument.writeln('<P>myCapString.indexOf(\"cheddar\") is ' + myCapString.indexOf(\"cheddar\"))\n
\n\nThe following example sets count to the number of occurrences of the letter x in the string str:
\n\ncount = 0;\npos = str.indexOf(\"x\");\nwhile ( pos != -1 ) {\n count++;\n pos = str.indexOf(\"x\",pos+1);\n}\n
\nA string representing the value to search for.
\nThe location within the calling string to start the search from. It can be any integer between 0 and\nthe length of the string. The default value is 0.
\nPosition of specified value or -1 if not found.
\nReturns the index within the calling String object of the last occurrence of\nthe specified value, or -1 if not found. The calling string is searched\nbackward, starting at fromIndex.
\n\nCharacters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character\nis stringName.length - 1
.
\"canal\".lastIndexOf(\"a\") // returns 3\n\"canal\".lastIndexOf(\"a\",2) // returns 1\n\"canal\".lastIndexOf(\"a\",0) // returns -1\n\"canal\".lastIndexOf(\"x\") // returns -1\n
\n\nThe lastIndexOf
method is case sensitive. For example, the following expression returns -1:
\"Blue Whale, Killer Whale\".lastIndexOf(\"blue\")\n
\n\nThe following example uses indexOf
and lastIndexOf
to locate values in the string \"Brave new world
\".
var anyString=\"Brave new world\"\n\n// Displays 8\ndocument.write(\"<P>The index of the first w from the beginning is \" +\nanyString.indexOf(\"w\"))\n// Displays 10\ndocument.write(\"<P>The index of the first w from the end is \" +\nanyString.lastIndexOf(\"w\"))\n// Displays 6\ndocument.write(\"<P>The index of 'new' from the beginning is \" +\nanyString.indexOf(\"new\"))\n// Displays 6\ndocument.write(\"<P>The index of 'new' from the end is \" +\nanyString.lastIndexOf(\"new\"))\n
\nA string representing the value to search for.
\nThe location within the calling string to start the search from, indexed from left to right. It can\nbe any integer between 0 and the length of the string. The default value is the length of the string.
\nReturns a number indicating whether a reference string comes before or after or is the same as the\ngiven string in sort order.
\n\nReturns a number indicating whether a reference string comes before or after or is the same as the\ngiven string in sort order. Returns -1 if the string occurs earlier in a sort than compareString
,\nreturns 1 if the string occurs afterwards in such a sort, and returns 0 if they occur at the same\nlevel.
The following example demonstrates the different potential results for a string occurring before,\nafter, or at the same level as another:
\n\nalert('a'.localeCompare('b')); // -1\nalert('b'.localeCompare('a')); // 1\nalert('b'.localeCompare('b')); // 0\n
\nThe string against which the referring string is comparing.
\nReturns -1 if the string occurs earlier in a sort than\ncompareString, returns 1 if the string occurs afterwards in such a sort, and\nreturns 0 if they occur at the same level.
\nUsed to match a regular expression against a string.
\n\nIf the regular expression does not include the g
flag, returns the same result as regexp.exec(string)
.
If the regular expression includes the g
flag, the method returns an Array containing all matches. If there were no matches,\nthe method returns null
.
The returned Array has an extra input
property, which contains the regexp that generated it as a result. In addition,\nit has an index
property, which represents the zero-based index of the match in the string.
In the following example, match
is used to find \"Chapter\" followed by 1 or more numeric characters followed by a decimal point\nand numeric character 0 or more times. The regular expression includes the i
flag so that case will be ignored.
str = \"For more information, see Chapter 3.4.5.1\";\nre = /(chapter \\d+(\\.\\d)*)/i;\nfound = str.match(re);\ndocument.write(found);\n
\n\nThis returns the array containing Chapter 3.4.5.1,Chapter 3.4.5.1,.1
\n\n\"Chapter 3.4.5.1
\" is the first match and the first value remembered from (Chapter \\d+(\\.\\d)*)
.
\".1
\" is the second value remembered from (\\.\\d)
.
The following example demonstrates the use of the global and ignore case flags with match
. All letters A through E and a\nthrough e are returned, each its own element in the array
var str = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\nvar regexp = /[A-E]/gi;\nvar matches_array = str.match(regexp);\ndocument.write(matches_array);\n
\n\nmatches_array
now equals ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
.
A RegExp object. If a non-RegExp object obj
is passed, it is\nimplicitly converted to a RegExp by using new RegExp(obj)
.
Contains results of the match (if any).
\nUsed to find a match between a regular expression and a string, and to replace the matched substring\nwith a new substring.
\n\nThis method does not change the String
object it is called on. It simply returns a new string.
To perform a global search and replace, either include the g
flag in the regular expression or if\nthe first parameter is a string, include g
in the flags parameter.
The replacement string can include the following special replacement patterns:
\n\n\n | Pattern | \nInserts | \n
---|---|---|
\n | $$ | \n Inserts a $ . | \n
\n | $& | \nInserts the matched substring. | \n
\n | `$`` | \nInserts the portion of the string that precedes the matched substring. | \n
\n | $' | \nInserts the portion of the string that follows the matched substring. | \n
\n | $n or $nn | \n Where n or nn are decimal digits, inserts the _n_th parenthesized submatch string, provided the first | \n
\n | \n | argument was a RegExp object. | \n
You can specify a function as the second parameter. In this case, the function will be invoked after the match has been\nperformed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special\nreplacement patterns do not apply in this case.) Note that the function will be invoked multiple times for each full match to be\nreplaced if the regular expression in the first parameter is global.
\n\nThe arguments to the function are as follows:
\n\n\n | Possible Name | \nSupplied Value | \n
---|---|---|
\n | str | \n The matched substring. (Corresponds to $& above.) | \n
\n | p1, p2, ... | \n The _n_th parenthesized submatch string, provided the first argument to replace was a RegExp object. | \n
\n | \n | (Correspond to $1, $2, etc. above.) | \n
\n | offset | \nThe offset of the matched substring within the total string being examined. (For example, if the total string | \n
\n | \n | was \"abcd \", and the matched substring was \"bc \", then this argument will be 1.) | \n
\n | s | \nThe total string being examined. | \n
(The exact number of arguments will depend on whether the first argument was a RegExp
object and, if so, how many parenthesized\nsubmatches it specifies.)
The following example will set newString
to \"XXzzzz - XX , zzzz
\":
function replacer(str, p1, p2, offset, s)\n{\n return str + \" - \" + p1 + \" , \" + p2;\n}\nvar newString = \"XXzzzz\".replace(/(X*)(z*)/, replacer);\n
\n\nIn the following example, the regular expression includes the global and ignore case flags which permits replace to replace each\noccurrence of 'apples' in the string with 'oranges'.
\n\nvar re = /apples/gi;\nvar str = \"Apples are round, and apples are juicy.\";\nvar newstr = str.replace(re, \"oranges\");\nprint(newstr);\n
\n\nIn this version, a string is used as the first parameter and the global and ignore case flags are specified in the flags\nparameter.
\n\nvar str = \"Apples are round, and apples are juicy.\";\nvar newstr = str.replace(\"apples\", \"oranges\", \"gi\");\nprint(newstr);\n
\n\nBoth of these examples print \"oranges are round, and oranges are juicy.\"
\n\nIn the following example, the regular expression is defined in replace and includes the ignore case flag.
\n\nvar str = \"Twas the night before Xmas...\";\nvar newstr = str.replace(/xmas/i, \"Christmas\");\nprint(newstr);\n
\n\nThis prints \"Twas the night before Christmas...\"
\n\nThe following script switches the words in the string. For the replacement text, the script uses the $1 and $2 replacement\npatterns.
\n\nvar re = /(\\w+)\\s(\\w+)/;\nvar str = \"John Smith\";\nvar newstr = str.replace(re, \"$2, $1\");\nprint(newstr);\n
\n\nThis prints \"Smith, John\".
\n\nIn this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just\nbefore the match location. The important thing here is that additional operations are needed on the matched item before it is\ngiven back as a replacement.
\n\nThe replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the\nhyphen before returning.
\n\nfunction styleHyphenFormat(propertyName)\n{\n function upperToHyphenLower(match)\n {\n return '-' + match.toLowerCase();\n }\n return propertyName.replace(/[A-Z]/, upperToHyphenLower);\n}\n
\n\nGiven styleHyphenFormat('borderTop')
, this returns 'border-top'.
Because we want to further transform the result of the match before the final substitution is made, we must use a function.\nThis forces the evaluation of the match prior to the toLowerCase()
method. If we had tried to do this using the match without a\n function, the toLowerCase()
would have no effect.
var newString = propertyName.replace(/[A-Z]/, '-' + '$&'.toLowerCase()); // won't work\n
\n\nThis is because '$&'.toLowerCase()
would be evaluated first as a string literal (resulting in the same '$&'
) before using the\ncharacters as a pattern.
The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number\nending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function\n returns 100C. If the number is 0F, the function returns -17.77777777777778C.
\n\nThe regular expression test
checks for any number that ends with F. The number of Fahrenheit degree is accessible to the\nfunction through its second parameter, p1
. The function sets the Celsius number based on the Fahrenheit degree passed in a\nstring to the f2c
function. f2c
then returns the Celsius number. This function approximates Perl's s///e
flag.
function f2c(x)\n{\n function convert(str, p1, offset, s)\n {\n return ((p1-32) * 5/9) + \"C\";\n }\n var s = String(x);\n var test = /(\\d+(?:\\.\\d*)?)F\\b/g;\n return s.replace(test, convert);\n}\n
\nA RegExp object. The match is replaced by the return value of parameter #2.
\nA String that is to be replaced by newSubStr
.
The String that replaces the substring received from parameter #1. A\nnumber of special replacement patterns are supported; see the \"Specifying a string as a parameter\"\nsection below.
\nA function to be invoked to create the new substring (to put in place\nof the substring received from parameter #1). The arguments supplied to this function are described\nin the \"Specifying a function as a parameter\" section below.
\nString of matched replaced items.
\nExecutes the search for a match between a regular expression and a specified string.
\n\nIf successful, search returns the index of the regular expression inside the string. Otherwise, it\nreturns -1.
\n\nWhen you want to know whether a pattern is found in a string use search (similar to the regular\nexpression test
method); for more information (but slower execution) use match
(similar to the\nregular expression exec
method).
The following example prints a message which depends on the success of the test.
\n\nfunction testinput(re, str){\n if (str.search(re) != -1)\n midstring = \" contains \";\n else\n midstring = \" does not contain \";\n document.write (str + midstring + re);\n}\n
\nA regular expression object. If a non-RegExp object obj is passed, it is\nimplicitly converted to a RegExp by using new RegExp(obj)
.
If successful, search returns the index of the regular\nexpression inside the string. Otherwise, it returns -1.
\nExtracts a section of a string and returns a new string.
\n\nslice
extracts the text from one string and returns a new string. Changes to the text in one\nstring do not affect the other string.
slice
extracts up to but not including endSlice
. string.slice(1,4)
extracts the second\ncharacter through the fourth character (characters indexed 1, 2, and 3).
As a negative index, endSlice
indicates an offset from the end of the string. string.slice(2,-1)
\nextracts the third character through the second to last character in the string.
The following example uses slice to create a new string.
\n\n// assumes a print function is defined\nvar str1 = \"The morning is upon us.\";\nvar str2 = str1.slice(4, -2);\nprint(str2);\n
\n\nThis writes:
\n\nmorning is upon u\n
\nThe zero-based index at which to begin extraction.
\nThe zero-based index at which to end extraction. If omitted, slice
\nextracts to the end of the string.
All characters from specified start up to (but excluding)\nend.
\nSplits a String
object into an array of strings by separating the string into substrings.
The split
method returns the new array.
When found, separator
is removed from the string and the substrings are returned in an array. If\nseparator
is omitted, the array contains one element consisting of the entire string.
If separator
is a regular expression that contains capturing parentheses, then each time separator\nis matched the results (including any undefined results) of the capturing parentheses are spliced\ninto the output array. However, not all browsers support this capability.
Note: When the string is empty, split
returns an array containing one empty string, rather than an\nempty array.
The following example defines a function that splits a string into an array of strings using the\nspecified separator. After splitting the string, the function displays messages indicating the\noriginal string (before the split), the separator used, the number of elements in the array, and the\nindividual array elements.
\n\nfunction splitString(stringToSplit,separator)\n{\n var arrayOfStrings = stringToSplit.split(separator);\n print('The original string is: \"' + stringToSplit + '\"');\n print('The separator is: \"' + separator + '\"');\n print(\"The array has \" + arrayOfStrings.length + \" elements: \");\n\n for (var i=0; i < arrayOfStrings.length; i++)\n print(arrayOfStrings[i] + \" / \");\n}\n\nvar tempestString = \"Oh brave new world that has such people in it.\";\nvar monthString = \"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec\";\n\nvar space = \" \";\nvar comma = \",\";\n\nsplitString(tempestString, space);\nsplitString(tempestString);\nsplitString(monthString, comma);\n
\n\nThis example produces the following output:
\n\nThe original string is: \"Oh brave new world that has such people in it.\"\nThe separator is: \" \"\nThe array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. /\n\nThe original string is: \"Oh brave new world that has such people in it.\"\nThe separator is: \"undefined\"\nThe array has 1 elements: Oh brave new world that has such people in it. /\n
\n\nThe original string is: \"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec\"\nThe separator is: \",\"\nThe array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec /
\n\nIn the following example, split
looks for 0 or more spaces followed by a semicolon followed by 0\nor more spaces and, when found, removes the spaces from the string. nameList is the array returned\nas a result of split.
var names = \"Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand \";\nprint(names);\nvar re = /\\s*;\\s*\\/;\nvar nameList = names.split(re);\nprint(nameList);\n
\n\nThis prints two lines; the first line prints the original string, and the second line prints the\nresulting array.
\n\nHarry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand\nHarry Trump,Fred Barney,Helen Rigby,Bill Abel,Chris Hand\n
\n\nIn the following example, split looks for 0 or more spaces in a string and returns the first 3\nsplits that it finds.
\n\nvar myString = \"Hello World. How are you doing?\";\nvar splits = myString.split(\" \", 3);\nprint(splits);\n
\n\nThis script displays the following:
\n\nHello,World.,How\n
\n\nIf separator
contains capturing parentheses, matched results are returned in the array.
var myString = \"Hello 1 word. Sentence number 2.\";\nvar splits = myString.split(/(\\d)/);\nprint(splits);\n
\n\nThis script displays the following:
\n\nHello ,1, word. Sentence number ,2, .\n
\nSpecifies the character to use for separating the string. The separator is treated as a string or a\nregular expression. If separator is omitted, the array returned contains one element consisting of the entire string.
\nInteger specifying a limit on the number of splits to be found. The split method still splits on every\nmatch of separator, but it truncates the returned array to at most limit elements.
\nSubstrings are returned in an array.
\nReturns the characters in a string beginning at the specified location through the specified number\nof characters.
\n\nstart
is a character index. The index of the first character is 0, and the index of the last\ncharacter is 1 less than the length of the string. substr
begins extracting characters at start\nand collects length characters (unless it reaches the end of the string first, in which case it will\nreturn fewer).
If start
is positive and is greater than or equal to the length of the string, substr
returns an\nempty string.
If start
is negative, substr
uses it as a character index from the end of the string. If start\nis negative and abs(start) is larger than the length of the string, substr
uses 0 as the start\nindex. Note: the described handling of negative values of the start argument is not supported by\nMicrosoft JScript.
If length is 0 or negative, substr
returns an empty string. If length is omitted, substr
\nextracts characters to the end of the string.
Consider the following script:
\n\n// assumes a print function is defined\nvar str = \"abcdefghij\";\nprint(\"(1,2): \" + str.substr(1,2));\nprint(\"(-3,2): \" + str.substr(-3,2));\nprint(\"(-3): \" + str.substr(-3));\nprint(\"(1): \" + str.substr(1));\nprint(\"(-20, 2): \" + str.substr(-20,2));\nprint(\"(20, 2): \" + str.substr(20,2));\n
\n\nThis script displays:
\n\n(1,2): bc\n(-3,2): hi\n(-3): hij\n(1): bcdefghij\n(-20, 2): ab\n(20, 2):\n
\nLocation at which to begin extracting characters.
\nThe number of characters to extract.
\nModified string.
\nReturns the characters in a string between two indexes into the string.
\n\nsubstring extracts characters from indexA up to but not including indexB. In particular:\n* If indexA
equals indexB
, substring
returns an empty string.\n* If indexB
is omitted, substring extracts characters to the end of the string.\n* If either argument is less than 0 or is NaN
, it is treated as if it were 0.\n* If either argument is greater than stringName.length
, it is treated as if it were\nstringName.length
.
If indexA
is larger than indexB
, then the effect of substring is as if the two arguments were\nswapped; for example, str.substring(1, 0) == str.substring(0, 1)
.
The following example uses substring to display characters from the string \"Sencha\":
\n\n// assumes a print function is defined\nvar anyString = \"Sencha\";\n\n// Displays \"Sen\"\nprint(anyString.substring(0,3));\nprint(anyString.substring(3,0));\n\n// Displays \"cha\"\nprint(anyString.substring(3,6));\nprint(anyString.substring(6,3));\n\n// Displays \"Sencha\"\nprint(anyString.substring(0,6));\nprint(anyString.substring(0,10));\n
\n\nThe following example replaces a substring within a string. It will replace both individual\ncharacters and substrings
. The function call at the end of the example changes the string \"Brave\nNew World\" into \"Brave New Web\".
function replaceString(oldS, newS, fullS) {\n // Replaces oldS with newS in the string fullS\n for (var i = 0; i < fullS.length; i++) {\n if (fullS.substring(i, i + oldS.length) == oldS) {\n fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length,\n
\n\nfullS.length);
\n\n }\n }\n return fullS;\n}\n\nreplaceString(\"World\", \"Web\", \"Brave New World\");\n
\nAn integer between 0 and one less than the length of the string.
\nAn integer between 0 and the length of the string.
\nReturns the characters in a string between two indexes into the string.
\nThe characters within a string are converted to lower case while respecting the current locale. For\nmost languages, this will return the same as toLowerCase
.
The toLocaleLowerCase
method returns the value of the string converted to lower case according to\nany locale-specific case mappings. toLocaleLowerCase
does not affect the value of the string\nitself. In most cases, this will produce the same result as toLowerCase()
, but for some locales,\nsuch as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may\nbe a different result.
The following example displays the string \"sencha\":
\n\nvar upperText=\"sencha\";\ndocument.write(upperText.toLocaleLowerCase());\n
\nReturns value of the string in lowercase.
\nThe characters within a string are converted to upper case while respecting the current locale. For\nmost languages, this will return the same as toUpperCase
.
The toLocaleUpperCase
method returns the value of the string converted to upper case according to\nany locale-specific case mappings. toLocaleUpperCase
does not affect the value of the string\nitself. In most cases, this will produce the same result as toUpperCase()
, but for some locales,\nsuch as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may\nbe a different result.
The following example displays the string \"SENCHA\":
\n\nvar lowerText=\"sencha\";\ndocument.write(lowerText.toLocaleUpperCase());\n
\nReturns value of the string in uppercase.
\nReturns the calling string value converted to lower case.
\n\nThe toLowerCase
method returns the value of the string converted to lowercase. toLowerCase
does\nnot affect the value of the string itself.
The following example displays the lowercase string \"sencha\":
\n\nvar upperText=\"SENCHA\";\ndocument.write(upperText.toLowerCase());\n
\nReturns value of the string in lowercase.
\nReturns a string representing the specified object. Overrides the Object.toString
method.
The String
object overrides the toString
method of the Object
object; it does not inherit\nObject.toString
. For String
objects, the toString
method returns a string representation of\nthe object.
The following example displays the string value of a String object:
\n\nx = new String(\"Hello world\");\nalert(x.toString()) // Displays \"Hello world\"\n
\nA string representation of the object.
\nReturns the calling string value converted to uppercase.
\n\nThe toUpperCase
method returns the value of the string converted to uppercase. toUpperCase
does\nnot affect the value of the string itself.
The following example displays the string \"SENCHA\":
\n\nvar lowerText=\"sencha\";\ndocument.write(lowerText.toUpperCase());\n
\nReturns value of the string in uppercase.
\nReturns the primitive value of the specified object. Overrides the Object.valueOf
method.
The valueOf
method of String returns the primitive value of a String
object as a string data\ntype. This value is equivalent to String.toString
.
This method is usually called internally by JavaScript and not explicitly in code.
\n\nx = new String(\"Hello world\");\nalert(x.valueOf()) // Displays \"Hello world\"\n
\nReturns value of string.
\n