谢氏工作室 - 我的精彩
我的鬼迹~~~~<br> 我的网路生活~~~<br> 我的~~~~~~~~~~~~~<br> Email:mrshelly@hotmail.com


JS正则分割重组排序的实例。
时间: 2004-10-26

<SCRIPT LANGUAGE="JavaScript1.2">

// The name string contains multiple spaces and tabs,
// and may have multiple spaces between first and last names.
names = new String ( "Harry Trump ;Fred Barney; Helen Rigby ;\
       Bill Abel ;Chris Hand ")

document.write ("---------- Original String" + "<BR>" + "<BR>");
document.write (names + "<BR>" + "<BR>");

// Prepare two regular expression patterns and array storage.
// Split the string into array elements.

// pattern: possible white space then semicolon then possible white space
pattern = /\s*;\s*/;

// Break the string into pieces separated by the pattern above and
// and store the pieces in an array called nameList
nameList = names.split (pattern);

// new pattern: one or more characters then spaces then characters.
// Use parentheses to "memorize" portions of the pattern.
// The memorized portions are referred to later.
pattern = /(\w+)\s+(\w+)/;

// New array for holding names being processed.
bySurnameList = new Array;

// Display the name array and populate the new array
// with comma-separated names, last first.
//
// The replace method removes anything matching the pattern
// and replaces it with the memorized string—second memorized portion
// followed by comma space followed by first memorized portion.
//
// The variables $1 and $2 refer to the portions
// memorized while matching the pattern.

document.write ("---------- After Split by Regular Expression" + "<BR>");
for ( i = 0; i < nameList.length; i++) {
   document.write (nameList[i] + "<BR>");
   bySurnameList[i] = nameList[i].replace (pattern, "$2, $1")
}

// Display the new array.
document.write ("---------- Names Reversed" + "<BR>");
for ( i = 0; i < bySurnameList.length; i++) {
   document.write (bySurnameList[i] + "<BR>")
}

// Sort by last name, then display the sorted array.
bySurnameList.sort();
document.write ("---------- Sorted" + "<BR>");
for ( i = 0; i < bySurnameList.length; i++) {
   document.write (bySurnameList[i] + "<BR>")
}

document.write ("---------- End" + "<BR>")

</SCRIPT>


 

执行结果:



shelly   发表于   2004-10-26 15:56:15    引用(Trackback0)

评论
发表评论

用户名:

Email:

主页:


   
最后更新


=================
.::水盟论坛::.
.::三 人 行::.
=================
.::胡言乱语::.
=================
.::蓝雨空间::.
.::好      人::.
.::安安心情::.
.::小戴网络::.
.::世纪网络::.
.::花开涂鸦::.
.::最新代理::.
.::凡凡纪事::.
.::喜悦国际村::.
.::TROYOO超越::.
=================
.::郭爽的BLOG::.
Microsoft Access Developers' Blog
=================
.::网站开发日志::.

=================
.::艺 壶 网::.

=================




本站提供大量电脑技术文章,欢迎浏览!