javascript字符串操作集锦和数组

http://www.k167.com/tech/web/jc/200612/74641.html
http://www.cnblogs.com/simonlhx/archive/2006/06/13/javascript.html
http://blog.csdn.net/guoguo1980/archive/2006/06/27/840802.aspx
http://www.soft6.com/know/detail.asp?id=BACGHB

JavaScript 操作字符串
 

虽 然 JavaScript 有很多用处,但是处理字符串是其中最流行的一个。下面让我们深入地分析一下使用 JavaScript 操作字符串。在 JavaScript 中, String 是对象。 String 对象并不是以字符数组的方式存储的,所以我们必须使用内建函数来操纵它们的值。这些内建函数提供了不同的方法来访问字符串变量的内容。下面我们详细看一下 这些函数。

包罗万象

操作字符串的值是一般的开发人员必须面临的家常便饭。操作字符串的具体方式有很多,比如说从一个字符串是提取出一部分内容来,或者确定一个字符串是否包含一个特定的字符。下面的 JavaScript 函数为开发人员提供了他们所需要的所有功能:

•  concat() – 将两个或多个字符的文本组合起来,返回一个新的字符串。

•  indexOf() – 返回字符串中一个子串第一处出现的索引。如果没有匹配项,返回 -1 。

•  charAT() – 返回指定位置的字符。

•  lastIndexOf() – 返回字符串中一个子串最后一处出现的索引,如果没有匹配项,返回 -1 。

•  match() – 检查一个字符串是否匹配一个正则表达式。

•  substring() – 返回字符串的一个子串。传入参数是起始位置和结束位置。

•  replace() – 用来查找匹配一个正则表达式的字符串,然后使用新字符串代替匹配的字符串。

•  search() – 执行一个正则表达式匹配查找。如果查找成功,返回字符串中匹配的索引值。否则返回 -1 。

•  slice() – 提取字符串的一部分,并返回一个新字符串。

•  split() – 通过将字符串划分成子串,将一个字符串做成一个字符串数组。

•  length() – 返回字符串的长度,所谓字符串的长度是指其包含的字符的个数。

•  toLowerCase() – 将整个字符串转成小写字母。

•  toUpperCase() – 将整个字符串转成大写字母。

注意: concat 、 match 、 replace 和 search 函数是在 JavaScript 1.2 中加入的。所有其它函数在 JavaScript 1.0 就已经提供了。

下面让我们看一下如何在 JavaScript 使用这些函数。下面的代码是用到了前面提到的所有函数:

function manipulateString(passedString1, passedString2) {

var concatString;

// The string passed to concat is added to the end of the first string

concatString = passedString1.concat(passedString2);

alert(concatString);

// The following if statement will be true since first word is Tony

if (concatString.charAt(3) == "y") {

alert("Character found!");

}

// The last position of the letter n is 10

alert("The last index of n is: " + concatString.lastIndexOf("n"));

// A regular expression is used to locate and replace the substring

var newString = concatString.replace(/Tony/gi,"General");

// The following yields Please salute General Patton

alert("Please salute " + newString);

// The match function returns an array containing all matches found

matchArray = concatString.match(/Tony/gi);

for (var i=0; i<matchArray.length;i++) {

alert("Match found: " + matchArray[i]);

}

// Determine if the regular expression is found, a –1 indicates no

if (newString.search(/Tony/) == -1) {

alert("String not found");

} else {

alert("String found.");

}

// Extract a portion of the string and store it in a new variable

var sliceString = newString.slice(newString.indexOf("l")+2,newString.length);

alert(sliceString);

// The split function creates a new array containing each value separated by a space

stringArray = concatString.split(" ");

for (var i=0; i<stringArray.length;i++) {

alert(stringArray[i];

}

alert(newString.toUpperCase());

alert(newString.toLowerCase());

}

下面是执行上面的代码得到的结果:

Tony Patton
Character Found!
The last index of n is: 10
Match found: Tony
Please salute General Patton
String not found
Patton
Tony
Patton
GENERAL PATTON
general patton

示例代码把所有这些提到的函数都用到了。

特殊字符

除了这些函数之外,还有很多的特殊字符可以用来表示关键的效果。这些特殊字符包括:

•  /t – 跳格键

•  /b – 退格 / 删除

•  /r – 回车

•  /n – 换行

•  /f – 换页

特 殊字符最常见的用途就是格式化输出。例如,你可能需要在输出中插入一个换行来正确地显示一个值。而且,在换行时也需要回车。在一些平台上,“ /n ”已经足够产生换行效果了,而在一些机器上要正确地显示一个换行则需要“ /r/n ”。下面的例子显示了在一个多行窗口上显示的特殊字符:

var output = null;
output = "Special Characters";
output += "/n";
output += "===============";
output += "/n";
output += "//t - tab";
output += "/n";
output += "//b - backspace/delete";
output += "/n";
output += "//r - carriage return";
output += "/n";
output += "//n - newline";
output += "/n";
output += "//f - form feed";
output += "/n";
alert(output);

前 面的例子使用加号来连接字符串,而没有使用 concat 函数。原因很简单,对于 concat 函数来说,每一个操作都需要一个新的变量;反之,我们这里用的这种方法则简单地扩展了原有的值,而不需要新的变量。而且,示例中使用换码符来正确地显示特 殊字符。系统将一个反斜线当作一个信号,认为它后面会跟一个特殊字符,但是连着两个反斜线则抵消这种操作。输出中的每个字符都通过 newline 特殊字符被显示在新的一行。

添加到工具箱中

特殊字符和函数可以与其它 JavaScript 技巧结合起来解决很多问题。其中一种情况是用来进行 JavaScript 客户端表单验证,这篇文章中提出的方法可以简单地用来实现表单验证。

下面的代码将在一个表单被提交时调用。要提交的表单包含三个域:名称、地址和邮政编码。为了实现起来比较简单,我们只验证每个域都不能为空,并且邮政编码必须是数字。下面的 JavaScript 代码完成这一功能:

function validation() {

var doc = document.forms[0];

var msg = "";

if (doc.Name.value == "") {

msg += "- Name is missing/n";

}

if (doc.Address.value == "") {

msg += "- Address is missing/n";

}

if (doc.ZipCode.value == "") {

msg += "- Zip code is missing/n";

}

var zip = new String(doc.ZipCode.value);

if (zip.search(/^[0-9][0-9][0-9][0-9][0-9]$/)==-1) {

msg += "- Enter valid Zip code";

}

if (msg == "") {

doc.submit;

} else {

msg = "Please correct the following validation errors and re-submit:/n/n" + msg;

alert(msg);

}

}

在用户提交表单时,这个函数就会被调用。对函数的调用是在一个 HTML 按钮的 onSubmit 事件中实现的。

<input type="button" type="submit" value="submit" onClick="validation()">

验 证函数检查每个域是否为空。如果发现了一个空值,那么就会在验证消息变量 msg 后面添加一个出错消息。此外,还使用了一个正则表达式来验证邮政编码域的格式。在这里,我们只接受五位数的美国地区邮政编码。如果发现有任何错误(即 msg 变量不为空),那么程序就会显示一个错误消息;否则的话,程序就会提交表单。

一门强大的语言

JavaScript 已经发展成熟为一种功能完备的语言,能够用来构建强大的应用程序。它是对具有非连接性天性的 Web 界面的一个完美的补充,能够在不与 Web 服务器交互的情况下完成很多客户端操作。




http://www.comptechdoc.org/independent/web/cgi/javamanual/javaarray.html

JavaScript Array Object

Describes the JavaScript aray object including parameters, properties, and methods.

Parameters

  • arrayLength
  • elementN - Array element list of values

Properties

  • index
  • input
  • length - The quantity of elements in the object.
  • prototype - For creating more properties.

Methods

  • chop() - Used to truncate the last character of a all strings that are part of an array. This method is not defined so it must be written and included in your code.
    var exclamations = new Array("Look out!", "Duck!" )
    exclamations.chop()

    Causes the values of exclamations to become:

    Look out
    Duck
  • concat()
  • grep(searchstring) - Takes an array and returns those array element strings that contain matching strings. This method is not defined so it must be written and included in your code.
    words = new Array("limit","lines","finish","complete","In","Out")
    inwords = words.grep("in")

    The array, inwords, will be:

    lines, finish
  • join(delimiter) - Puts all elements in the array into a string, separating each element with the specified delimiter.
    words = new Array("limit","lines","finish","complete","In","Out")
    var jwords = words.join(";")

    The value of the string jwords is:

    limit;lines;finish;complete;In;Out
  • pop() - Pops the last string off the array and returns it. This method is not defined so it must be written and included in your code.
    words = new Array("limit","lines","finish","complete","In","Out")
    var lastword = words.pop()

    The value of the string lastword is:

    Out
  • push(strings) - Strings are placed at the end of the array. This method is not defined so it must be written and included in your code.
    words = new Array("limit","lines","finish")
    words.push("complete","In","Out")

    The array, words, will be:

    limit, lines, finish, complete, In, Out
  • reverse() - Puts array elements in reverse order.
    words = new Array("limit","lines","finish","complete","In","Out")
    words.reverse()

    The array, words, will be:

    Out, In, complete, finish, lines, limit
  • shift() - Decreases array element size by one by shifting the first element off the array and returning it. This method is not defined so it must be written and included in your code.
    words = new Array("limit","lines","finish","complete","In","Out")
    word = words.shift()

    The array, words, will be:

    In, complete, finish, lines, limit

    The string word will be:

    Out
  • sort() - Sorts the array elements in dictionary order or using a compare function passed to the method.
    words = new Array("limit","lines","finish","complete","In","Out")
    word = words.sort()

    The value of words becomes:

    In,Out,complete,finish,limit,lines
  • splice() - It is used to take elements out of an array and replace them with those specified. In the below example the element starting at element 3 is removed, two of them are removed and replaced with the specified strings. The value returned are those values that are replaced. This method is not defined so it must be written and included in your code.
    words = new Array("limit","lines","finish","complete","In","Out")
    words1 = words.splice(3, 2, "done", "On")

    The value of words becomes:

    limit, lines, finish, done, On, Out

    The value of words1 is set to:

    complete, In
  • split(deliimiter) - Splits a string using the delimiter and returns an array.
    words = new String("limit;lines;finish;complete;In;Out")
    var swords = words.split(";")

    The values in the array swords is:

    limit, lines, finish, complete, In, Out
  • unshift() - Places elementa at the start of an array
    words = new Array("finish","complete","In","Out")
    word = words.shift("limit","lines")

    The array, words, will be:

    limit, lines,finish, complete, In, Out
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值