42. parseInt() / parseFolat()
<script type="text/javascript">
//<![CDATA[
var str='1.1322 this test ';
document.write(('str like this: ').bold()+str.fontcolor('red')+'<br/>');
document.write(('parseInt(str): ').bold()+parseInt(str)+'<br/>');
document.write(('parseFloat(str): ').bold()+parseFloat(str)+'<br/>');
31.7 定义函数变量, 并赋值
<script type="text/javascript">
//<![CDATA[
var t=(function(str){return str+str+'<br/>';})('test this ')
document.write(t);
//]]>
</script>
31.8 变量引用函数
<script type="text/javascript">
//<![CDATA[
function t(x){
x+='';
return x+x;
}
document.write(t('how fun ')+'<br>'); // how fun how fun
var u=t // u 引用 函数 t
document.write(u('how fun too ')+'<br>'); // how fun too how fun too
//]]>
</script>
31.9 在对象中存储函数, 并引用
<script type="text/javascript">
//<![CDATA[
var o=new Object();
o.t=function(x){x+=''; return x+x;}
var t=o.t('test this ');
document.write(t);
//]]>
</script>
31.10 在数组中存储函数, 并引用
<script type="text/javascript">
//<![CDATA[
var a=new Array(3);
a[0]=function(x){x+='';return x+x};
a[1]='test this ';
a[2]=a[0](a[1]);
document.write(a[2]);
//]]>
</script>
31.11 function.call()
<script type="text/javascript">
//<![CDATA[
var o=new Object();
function f(a, b){
return a+b
}
document.write(f.call(o, 1, 2));
//]]>
</script>
31.12 在函数内定义的变量可以被下级内嵌函数调用
<script type="text/javascript">
//<![CDATA[
function t(){
var x=" this's test ";
function u(){
document.write(x.bold());
}
u();
}
t();
//]]>
</script>
29. isNaN
<script type="text/javascript">
//<![CDATA[
var $str='this is string';
var $num=12.3;
//alert(isNaN($str));
alert(isNaN($num));
//]]>
</script>
28. new 语法
new Boolean(false)
new Number(0)
new String("")
new Array()
new Object()
new Date();
new Error();
27. RegExp
27.1 普通操作 1
<script type="text/javascript">
//<![CDATA[
var $str='this is a test'
with(document){
write('test str is: '+$str+'<br/>');
write('$str.search(/is a/i): '+$str.search(/is a/i)+'<p/>');
var $temp=$str.match(/(t[\S]{1,3})/ig)
for ($i=0; $i<$temp.length; $i++){
write($temp[$i]+'<br/>');
}
}
//]]>
</script>
27.2 test 语句
<script type="text/javascript">
//<![CDATA[
var $pattern=/this/i;
alert($pattern.test('this is a test'));
//]]>
</script>
27.3 exec 语句
<script type="text/javascript">
//<![CDATA[
var $pattern=/this/ig;
var $str='this is a test, this is repeat';
var $result;
while(($result=$pattern.exec($str))!=null){
alert($result[0]+'>>> index of str: '+$result.index+' $pattern lastIndex: '+$pattern.lastIndex);
}
//]]>
</script>
24.2.1 创建嵌套对象 1
<script type="text/javascript">
//<![CDATA[
var o=new Object();
o.title=' this title ';
o.content=' this content';
o.lve=new Object();
o.lve.title=' this o.lve title';
o.lve.content=' this o.lve content';
var $name="";
for(name in $obj)$name+=name+'\n';
alert($name);
//]]>
</script>
24.4.1 遍历对象中的属性名 1
<script type="text/javascript">
//<![CDATA[
var o=new Object();
o.title=' this title ';
o.content=' this content';
o.lve=new Object();
o.lve.title=' this o.lve title';
o.lve.content=' this o.lve content';
for (var i in o){
if(typeof o[i]!=='object'){
document.write('object o, element: '+i.fontcolor('red')+' value: '+o[i].bold()+'<br/>');
} else {
document.write('object '+i+' element<br/>');
for(var j in o[i]){
document.write('subobject element :'+j.fontcolor('red')+
' subobject value: '+o[i][j].bold()+'<br/>');
}
}
}
//]]>
</script>
24.5 obj.propertyIsEnumerable('ele')
<script type="text/javascript">
//<![CDATA[
var d=new Date();
d.x='test';
var s=new String();
var o=new Object();
var f=new Function('thest')
24.6 obj.hasOwnProperty('ele')
<script type="text/javascript">
//<![CDATA[
var d=new Date();
d.x='test';
var s=new String();
var o=new Object();
var f=new Function('thest')
document.write('<h2>window object:</h2>');
for(var i in window){
try{
document.write(i.bold()+' '+(window[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
/*
document.write('<h2>Option object:</h2>');
for(var i in Option){
try{
document.write(i.bold()+' '+(Option[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
*/
document.write('<h2>frames object:</h2>');
for(var i in frames){
try{
document.write(i.bold()+' '+(frames[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
/*
document.write('<h2>self object:</h2>');
for(var i in self){
try{
document.write(i.bold()+' '+(self[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
*/
document.write('<h2>document object:</h2>');
for(var i in document){
document.write(i.bold()+' '+(document[i]+'').fontcolor('blue')+'<br/>');
}
document.write('<h2>history object:</h2>');
for(var i in history){
try{
document.write(i.bold()+' '+(history[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
/*
document.write('<h2>Image object:</h2>');
for(var i in Image){
try{
document.write(i.bold()+' '+(Image[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
*/
document.write('<h2>navigator object:</h2>');
for(var i in navigator){
try{
document.write(i.bold()+' '+(navigator[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
document.write('<h2>location object:</h2>');
for(var i in location){
document.write(i.bold()+' '+(location[i]+'').fontcolor('blue')+'<br/>');
}
//]]>
</script>
19.1.1 简单 for in 1
for (var $i in window){
document.write($i+'<br/>');
}
19.2 for in 赋值 [数组]
var $array=new Array();
var i=0;
for ($array[i++] in window){
//document.write($i+'<br/>');
}
alert($array[0]);
19.2.1 for in 赋值 [数组] 1
<script type="text/javascript">
//<![CDATA[
var o={a:'aaa', b:'bbb', c:'ccc'};
var a=new Array();
var i=0;
for(a[i++] in o)document.write(a[i-1]);
//for(i in a)document.write(a[i]);
//]]>
</script>
18. for
18.1 简单 for
for (var $i=0; $i<10; $i++) {
document.write($i)
}
18.2 简单 for 1
for (var $i=0, $j=10; $i<10; $i++, $j--) {
document.write(($i*$j)+'<br/>')
}
18.3 循环列出从 a - z 的字母
<script type="text/javascript">
//<![CDATA[
for(var $i='a'.charCodeAt(); $i<='z'.charCodeAt(); $i++){
document.write(String.fromCharCode($i)+'<br/>')
}
//]]>
</script>
18.3 n阶乘
<script type="text/javascript">
//<![CDATA[
var $fN=10
for (var $i=1, $j=1; $i<=$fN; $i++, $j*=$i){
if($i==$fN){document.write($j);}
}
//]]>
</script>
17.1 简单 do while
var $count=0
do{
document.write($count)
} while(++$count<10)
17.1.2 简单 do while
var $count=1
do{
document.write($count)
} while($count++<10)
16. while
16. 简单 while
var $count=0
while($count<10){ document.write($count);$count++;}
15 if 判断
15.1 简单 if 判断
function ubbTag(fId, str){
document.getElementById(fId).content.focus();
var strEnd=str.replace(//ig,'[/')
if (strEnd.indexOf('=')>-1){ strEnd=strEnd.replace(/(.*?)\=.*?
/ig,'[/') if (strEnd.indexOf('=')>-1){ strEnd=strEnd.replace(/(.*?)\=.*?
15.2 if 判断的 三个 写法
<script type="text/javascript">
//<![CDATA[
var a=b=5, c=6
if(a==b)document.write('a equal b <br/>');
(a==b)&&document.write('a equal b <br/>');
a==b?document.write('a equal b <br/>'):'';
//]]>
</script>
14.1 简单 switch
/* switch(strEnd){
case '\[\/html]' :strEnd=strEnd.replace(/\\[\/,'HTML 和 JS 代码支持[');break;
case '\[\/code]' :strEnd=strEnd.replace(/\\[\/,'代码[');break;
case '\[\/quote]' :strEnd=strEnd.replace(/\\[\/,'引用[');break;
case '\[\/cite]' :strEnd=strEnd.replace(/\\[\/,'引用[');break;
case '\[\/linenum]' :strEnd=strEnd.replace(/\\[\/,'显示行号[');break;
case '\[\/b]' :strEnd=strEnd.replace(/\\[\/,'粗体[');break;
case '\[\/i]' :strEnd=strEnd.replace(/\\[\/,'叙体[');break;
case '\[\/u]' :strEnd=strEnd.replace(/\\[\/,'下划线[');break;
case '\[\/flash]' :strEnd=strEnd.replace(/\\[\/,'Flash 动画[');break;
case '\[\/sound]' :strEnd=strEnd.replace(/\\[\/,'背景声音[');break;
case '\[\/mms]' :strEnd=strEnd.replace(/\\[\/,'WM格式流数据[');break;
case '\[\/rtsp]' :strEnd=strEnd.replace(/\\[\/,'Real格式流数据[');break;
case '\[\/ra]' :strEnd=strEnd.replace(/\\[\/,'在线Real Player播放音频文件[');break;
case '\[\/real]' :strEnd=strEnd.replace(/\\[\/,'Real Player 播放视频文件[');break;
case '\[\/wm]' :strEnd=strEnd.replace(/\\[\/,'在线Windows Media Player播放视频文件[');break;
case '\[\/wma]' :strEnd=strEnd.replace(/\\[\/,'在线Windows Media Player播放音频文件[');break;
case '\[\/iframe]' :strEnd=strEnd.replace(/\\[\/,'插入网页[');break;
} */
13. 时间操作
13.1 以毫秒为单位的倒计时跳转, 来源 CSDN
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
//<![CDATA[
var go=20000;
var timer=null;
var endTime = new Date().getTime() + go ;
function interval()
{
var n=(endTime-new Date().getTime())/1000;
if(n<0) return;
document.getElementById("jumpTo").innerHTML = n.toFixed(3);
setTimeout(interval, 10);
}
window.οnlοad=function(){
timer=setTimeout("window.location.href='/'", go);
interval();
}
//]]>
</script>
<span id="jumpTo">20.000</span> 秒后 将自动</span>跳转到
12. 随机数
12.1 生成 GUID
<!--start 12.1-->
<html>
<!-- DW6 -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script>
function fGuid()
{
var g ="";
for(var i = 0; i < 32; i++)
g += Math.floor(Math.random() * 0xF).toString(0xF) + (i == 8 || i == 12 || i == 16 || i == 20 ? "-" : "");
alert(g.toUpperCase());
}
</script>
</head>
<body onLoad="fGuid();">
</body>
</html>
<!--end 12.1-->
12.1.1 生成 GUID 2
<!--start 12.1.1 -->
<html>
<!-- DW6 -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script>
function fGuid() {
var g ="";
for(var i = 0; i < 32; i++)
g += Math.floor(Math.random() * 0xF).toString(0xF) + (i == 8 || i == 12 || i == 16 || i == 20 ? "-" : "");
//alert(g.toUpperCase());
return g.toUpperCase();
}
</script>
</head>
<body>
<form name="form1" method="post" action="">
<input name="textfield" type="text" onMouseMove="this.value=fGuid();" size="50">
</form>
</body>
</html>
<!--end 12.1.1 -->
3.1 Javascript 结合 Asp 使用数组
<% '连接数据库
set rs=server.CreateObject("adodb.recordset") '创建 rs 数据查询
rs.open "Select a.*, b.* FROM ctglossarysubcat AS a INNER JOIN ctglossarysupercat AS b ON a.gcid = b.gcid order by a.gcid",MM_conn_string,1
%>
<script LANGUAGE="JAVASCRIPT">
var onecount; //定义子类计数
onecount=0; //设置子类计数默认值为0
subcat = new Array(); //定义显示子类数组
<% count = 0
do while not rs.eof %>
subcat[<%=count%>] = new Array("<%=rs("gscat")%>","<%=rs("a.gcid")%>","<%=rs("gscid")%>");
<% count = count + 1
rs.movenext
loop
%>
onecount=<%=count%>; //子类条目总数
</script>
<%
rs.close '关闭 rs 连接
set rs=nothing
%>
-2.2 全局变量与局部变量
<script type="text/javascript">
//<![CDATA[
var i='global i';//全局
function t(){
var i='local i'; //局部
document.write(i+'<br/>');
j='global j' //全局
document.write(j+'<br/>');
}
document.write(i+'<br/>');
t();
document.write(i+'<br/>');
document.write(j+'<br/>');
var k='global k'
document.write(k+'<br/>');
function t1(){
k='change global k'
document.write(k+'<br/>');
}
t1();
document.write(k+'<br/>');
//]]>
</script>
-2.3 在函数中使用 var 定义一个变量, 该变量将影响整个函数, 不分先后.
var scope = "global";
function f( ) {
alert(scope); // Displays "undefined", not "global"
var scope = "local"; // Variable initialized here, but defined everywhere
alert(scope); // Displays "local"
}
f( );
24. Keep in mind that the function statement is available in all versions of JavaScript, the Function( ) constructor is available only in JavaScript 1.1 and later, and function literals are available only in JavaScript 1.2 and later. Recall that we said the three functions defined earlier are "more or less" equivalent -- there are some differences between these three techniques for function definition, which we'll consider in Section 11.5.
//JavaScript: The Definitive Guide, 4th Edition -- 7.1.3 Function Literals
2006-10-19 14:35:56
23. The Function( ) constructor expects any number of string arguments. The last argument is the body of the function -- it can contain arbitrary JavaScript statements, separated from each other by semicolons. All other arguments to the constructor are strings that specify the names of the parameters to the function being defined. If you are defining a function that takes no arguments, you simply pass a single string -- the function body -- to the constructor.
//JavaScript: The Definitive Guide, 4th Edition -- 7.1.2 The Function( ) Constructor
2006-10-19 14:16:18
22. Note that ECMAScript v3 does not allow function definitions to appear anywhere; they are still restricted to top-level global code and top-level function code. This means that function definitions may not appear within loops or conditionals, for example.[1] These restrictions on function definitions apply only to function declarations with the function statement. As we'll discuss later in this chapter, function literals (another feature introduced in JavaScript 1.2 and standardized by ECMAScript v3) may appear within any JavaScript expression, which means that they can appear within if and other statements.
//JavaScript: The Definitive Guide, 4th Edition -- 7.1 Defining and Invoking Functions
2006-10-19 14:10:13
21. try and finally can be used together without a catch clause. In this case, the finally block is simply cleanup code that is guaranteed to be executed, regardless of any break, continue, or return statements within the try clause. For example, the following code uses a try/finally statement to ensure that a loop counter variable is incremented at the end of each iteration, even when an iteration terminates abruptly because of a continue statement:
20. The continue statement, in both its labeled and unlabeled forms, can be used only within the body of a while, do/while, for, or for/in loop. Using it anywhere else causes a syntax error.
19. The following rules are used to determine whether two values are identical according to the === operator:
If the two values have different types, they are not identical.
If both values are numbers and have the same value, they are identical, unless either or both values are NaN, in which case they are not identical. The NaN value is never identical to any other value, including itself! To check whether a value is NaN, use the global isNaN( ) function.
If both values are strings and contain exactly the same characters in the same positions, they are identical. If the strings differ in length or content, they are not identical. Note that in some cases, the Unicode standard allows more than one way to encode the same string. For efficiency, however, JavaScript string comparison compares strictly on a character-by-character basis, and it assumes that all strings have been converted to a "normalized form" before they are compared. See the "String.localeCompare( )" reference page in the core reference section of this book for another way to compare strings.
If both values are the boolean value true or both are the boolean value false, they are identical.
If both values refer to the same object, array, or function, they are identical. If they refer to different objects (or arrays or functions) they are not identical, even if both objects have identical properties or both arrays have identical elements.
If both values are null or both values are undefined, they are identical.
The following rules are used to determine whether two values are equal according to the == operator:
If the two values have the same type, test them for identity. If the values are identical, they are equal; if they are not identical, they are not equal.
If the two values do not have the same type, they may still be equal. Use the following rules and type conversions to check for equality:
If one value is null and the other is undefined, they are equal.
If one value is a number and the other is a string, convert the string to a number and try the comparison again, using the converted value.
If either value is true, convert it to 1 and try the comparison again. If either value is false, convert it to 0 and try the comparison again.
If one value is an object and the other is a number or string, convert the object to a primitive and try the comparison again. An object is converted to a primitive value by either its toString( ) method or its valueOf( ) method. The built-in classes of core JavaScript attempt valueOf( ) conversion before toString( ) conversion, except for the Date class, which performs toString( ) conversion. Objects that are not part of core JavaScript may convert themselves to primitive values in an implementation-defined way.
Any other combinations of values are not equal.
As an example of testing for equality, consider the comparison:
"1" == true
This expression evaluates to true, indicating that these very different-looking values are in fact equal. The boolean value true is first converted to the number 1, and the comparison is done again. Next, the string "1" is converted to the number 1. Since both numbers are now the same, the comparison returns true.
When the equality operator in JavaScript 1.1 attempted to convert a string to a number and failed, it displayed an error message noting that the string could not be converted, instead of converting the string to NaN and returning false as the result of the comparison. This bug has been fixed in JavaScript 1.2.
18. In top-level code (i.e., JavaScript code that is not part of a function), you can use the JavaScript keyword this to refer to the global object. Within functions, this has a different use, which is described in Chapter 7.
//JavaScript: The Definitive Guide, 4th Edition -- 4.6 Variables as Properties
2006-10-16 16:08:34
17. Garbage collection is automatic and is invisible to the programmer. You can create all the garbage objects you want, and the system will clean up after you! You need to know only enough about garbage collection to trust that it works; you don't have to wonder about where all the old objects go. For those who aren't satisfied, however, Section 11.3, contains further details on the JavaScript garbage-collection process.
16. Primitive Types and Reference Types
var a = [1,2,3]; // Initialize a variable to refer to an array
var b = a; // Copy that reference into a new variable
a[0] = 99; // Modify the array using the original reference
alert(b); // Display the changed array [99,2,3] using the new reference
If this result does not seem surprising to you, you're already well familiar with the distinction between primitive and reference types. If it does seem surprising, take a closer look at the second line. Note that it is the reference to the array value, not the array itself, that is being assigned in this statement. After that second line of code, we still have only one array object; we just happen to have two references to it.
//JavaScript: The Definitive Guide, 4th Edition -- 4.4 Primitive Types and Reference Types
14. The rule that all variables declared in a function are defined throughout the function can cause surprising results. The following code illustrates this:
var scope = "global";
function f( ) {
alert(scope); // Displays "undefined", not "global"
var scope = "local"; // Variable initialized here, but defined everywhere
alert(scope); // Displays "local"
}
f( );
//JavaScript: The Definitive Guide, 4th Edition -- 4.3 Variable Scope
13. Variable Scope
The scope of a variable is the region of your program in which it is defined. A global variable has global scope -- it is defined everywhere in your JavaScript code. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables and have local scope. Function parameters also count as local variables and are defined only within the body of the function.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. For example, the following code prints the word "local":
var scope = "global"; // Declare a global variable
function checkscope( ) {
var scope = "local"; // Declare a local variable with the same name
document.write(scope); // Use the local variable, not the global one
}
checkscope( ); // Prints "local"
12. In general, functions do not know what variables are defined in the global scope or what they are being used for. Thus, if a function uses a global variable instead of a local one, it runs the risk of changing a value upon which some other part of the program relies. Fortunately, avoiding this problem is simple: declare all variables with var
11. If you attempt to read the value of an undeclared variable, JavaScript will generate an error. If you assign a value to a variable that you have not declared with var, JavaScript will implicitly declare that variable for you. Note, however, that implicitly declared variables are always created as global variables, even if they are used within the body of a function. To prevent the creation of a global variable (or the use of an existing global variable) when you meant to create a local variable for use within a single function, you must always use the var statement within function bodies. It's best to use var for all variables, whether global or local. (The distinction between local and global variables is explored in more detail in the next section.)
//JavaScript: The Definitive Guide, 4th Edition -- 4.2.1 Repeated and Omitted Declarations
2006-10-15 22:00:53
10. Error Objects
ECMAScript v3 defines a number of classes that represent errors. The JavaScript interpreter "throws" an object of one of these types when a runtime error occurs. (See the throw and try statements in Chapter 6 for a discussion of throwing and catching errors.) Each error object has a message property that contains an implementation-specific error message. The types of predefined error objects are Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, and URIError. You can find out more about these classes in the core reference section of this book.
Another special value used occasionally by JavaScript is the undefined value returned when you use either a variable that has been declared but never had a value assigned to it, or an object property that does not exist. Note that this special undefined value is not the same as null.
Although null and the undefined value are distinct, the == equality operator considers them to be equal to one another. Consider the following:
my.prop == null
7. Both Netscape and Microsoft have made their JavaScript interpreters available to companies and programmers who want to embed them in their applications. Netscape's interpreter was released as open source and is now available through the Mozilla organization (see http://www.mozilla.org/js/). Mozilla actually provides two different versions of the JavaScript 1.5 interpreter. One is written in C and is called "SpiderMonkey." The other is written in Java and, in a flattering reference to this book, is called "Rhino."
//JavaScript: The Definitive Guide, 4th Edition -- 1.4 JavaScript in Other Contexts
2006-10-14 1:13:44
6. 11.1.2 Explicit Type Conversions
Table 11-1 listed the automatic data type conversions that JavaScript performs. It is also possible to explicitly convert values from one type to another. JavaScript does not define a cast operator as C, C++, and Java do, but it does provide similar facilities for converting data values.
As of JavaScript 1.1 (and the ECMA-262 standard), Number( ) , Boolean( ), String( ), and Object( ) may be called as functions as well as being invoked as constructors. When invoked in this way, these functions attempt to convert their arguments to the appropriate type. For example, you could convert any value x to a string with String(x) and convert any value y to an object with Object(y).
There are a few other tricks that can be useful for performing explicit conversions. To convert a value to a string, concatenate it with the empty string:
var x_as_string = x + "";
To force a value to a number, subtract zero from it:
var x_as_number = x - 0;
And to force a value to boolean, use the ! operator twice:
var x_as_boolean = !!x;
Because of JavaScript's tendency to automatically convert data to whatever type is required, explicit conversions are usually unnecessary. They are occasionally helpful, however, and can also be used to make your code clearer and more precise.
//JavaScript: The Definitive Guide, 4th Edition -- 11.1 Data Type Conversion
2006-10-12 12:36:23
5. Each RegExp object has five properties. The source property is a read-only string that contains the text of the regular expression. The global property is a read-only boolean value that specifies whether the regular expression has the g flag. The ignoreCase property is a read-only boolean value that specifies whether the regular expression has the i flag. The multiline property is a read-only boolean value that specifies whether the regular expression has the m flag. The final property is lastIndex, a read-write integer. For patterns with the g flag, this property stores the position in the string at which the next search is to begin. It is used by the exec( ) and test( ) methods, as described in the previous section.
4. the RegExp constructor. search( ) does not support global searches -- it ignores the g flag of its regular expression argument.
//JavaScript: The Definitive Guide, 4th Edition -- 10.2 String Methods for Pattern Matching
2006-10-9 19:56:40
3. We've seen the . operator used to access the properties of an object. It is also possible to use the [] operator, which is more commonly used with arrays, to access these properties. Thus, the following two JavaScript expressions have the same value:
object.property
object["property"]
//JavaScript: The Definitive Guide, 4th Edition -- 8.6 Objects as Associative Arrays
2006-10-9 14:45:13
2. The typeof Operator
typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value. It evaluates to "object" for objects, arrays, and (surprisingly) null. It evaluates to "function" for function operands and to "undefined" if the operand is undefined.
//JavaScript: The Definitive Guide, 4th Edition -- 5.10.2 The typeof Operator
1. JavaScript strings (and JavaScript arrays, as we'll see later) are indexed starting with zero.
5. str.split()
<script type="text/javascript">
//<![CDATA[
var str=' this , is, a, text';
document.write(str.split(/\s*,\s*/));
document.write('<br/>');
document.write(str.split(/\s*,\s*/).join());
//]]>
</script>
4. str.match()
<script type="text/javascript">
//<![CDATA[
var str=' This is a test. ';
document.write(str.match(/\w+/).join());
document.write('<br/>');
document.write(str.match(/\w+/g).join());
//]]>
</script>
3. str.replace()
<script type="text/javascript">
//<![CDATA[
var str=' This is a test. ';
document.write(str.replace(/^(\s+)|(\s+)$/,'----------'));
document.write('<br/>');
document.write(str.replace(/^(\s+)|(\s+)$/g,'----------'));
//]]>
</script>
2. str.search()
<script type="text/javascript">
//<![CDATA[
var str=' This is a test. ';
document.write(str.search(/this/i));
//]]>
</script>
1. 子匹配
<script type="text/javascript">
//<![CDATA[
var str=' this is a test '
document.write(str.match(/(is+).*?\1/)[0]);
//]]>
</script>
0. 创建正则表达式模式
0.1 new RegExp()
<script type="text/javascript">
//<![CDATA[
var str=' this is a test '
var re=new RegExp('\\w+','g');
document.write(str.match(re));
//]]>
</script>
-1. re.exec(str)
<script type="text/javascript">
//<![CDATA[
var str=' this is a test '
var pt=/this|test/g;
-2. re.test(str)
<script type="text/javascript">
//<![CDATA[
var str=' this is a test ';
var re=/\d+/;
document.write(re.test(str));
var re=/\w+/;
document.write(re.test(str));
//]]>
</script>
---/----------------------------------------
摘要:
4. The String methods search( ) , replace( ), and match( ) do not use the lastIndex property as exec( ) and test( ) do. In fact, the String methods simply reset lastIndex( ) to 0. If you use exec( ) or test( ) on a pattern that has the g flag set and you are searching multiple strings, you must either find all the matches in each string, so that lastIndex is automatically reset to zero (this happens when the last search fails), or you must explicitly set the lastIndex property to 0 yourself. If you forget to do this, you may start searching a new string at some arbitrary position within the string rather than from the beginning. Finally, remember that this special lastIndex behavior occurs only for regular expressions with the g flag. exec( ) and test( ) ignore the lastIndex property of RegExp objects that do not have the g flag.
//JavaScript: The Definitive Guide, 4th Edition -- 10.3.1 RegExp Methods for Pattern Matching
2006-10-20 18:10:36
3. match method
The match( ) method is the most general of the String regular expression methods. It takes a regular expression as its only argument (or converts its argument to a regular expression by passing it to the RegExp( ) constructor) and returns an array that contains the results of the match. If the regular expression has the g flag set, the method returns an array of all matches that appear in the string. For example:
"1 plus 2 equals 3".match(/\d+/g) // returns ["1", "2", "3"]
//JavaScript: The Definitive Guide, 4th Edition -- 10.2 String Methods for Pattern Matching
2006-10-20 17:23:08
2. search method
Strings support four methods that make use of regular expressions. The simplest is search( ). This method takes a regular expression argument and returns either the character position of the start of the first matching substring, or -1 if there is no match. For example, the following call returns 4:
"JavaScript".search(/script/i);
If the argument to search( ) is not a regular expression, it is first converted to one by passing it to the RegExp constructor. search( ) does not support global searches -- it ignores the g flag of its regular expression argument.
//JavaScript: The Definitive Guide, 4th Edition -- 10.2 String Methods for Pattern Matching
1. A number of punctuation characters have special meanings in regular expressions. They are:
^ $ . * + ? = ! : | \ / ( ) [ ] { }
//JavaScript: The Definitive Guide, 4th Edition -- 10.1 Defining Regular Expressions