---
title: "Javascript对字符串的处理"
author: "gift5168xf"
date: "2009-10-08T20:21:00Z"
tags: []
slug: "javascript"
draft: false
lastmod: "2009-10-14T01:45:11Z"
id: 487568
url: "https://sufery.iteye.com/blog/487568"
---

一、声明字符串:  
varnormal\_monkey="Iamamonkey!&lt;br&gt;";  
document.writeln("Normalmonkey"+normal\_monkey);

varbold\_monkey=normal\_monkey.bold();  
document.writeln("Boldmonkey"+bold\_monkey);

这里的声明：varbold\_monkey=normal\_monkey.bold();  
和下面对声明是等同的：  
varbold\_monkey="&lt;b&gt;"+normal\_monkey+"&lt;/b&gt;";

第1 个版本的声明看起来要简明得多。这里用到了字符串对象中  
的bold 对象，其他的字符串对象还有indexOf,charAt,  
substring, 以及split, 这些方法可以深入字符串的组成结构。  
首先我们研究一下indexOf 。

2 、indexOf  
indexOf 用于发现一系列的字符在一个字符串中等位置并告诉你子字符串的起始位置。如

果一个字符串中部包含该子字符串则indexOf 返回returns"-1."  
例子：  
varthe\_word="monkey";  
// 让我们从单词"monkey" 开始。  
varlocation\_of\_m=the\_word.indexOf("m");  
//location\_of\_m( 字母m 的位置) 将为0 ，因为字母m 位于该字符串的起始位置。  
varlocation\_of\_o=the\_word.indexOf("o");  
//location\_of\_o( 字母o 的位置) 将为1 。  
varlocation\_of\_key=the\_word.indexOf("key");  
//location\_of\_key(key 的位置) 将为3 因为子字符串“key” 以字母k 开始，而k

在单词monkey 中的位置是3 。  
varlocation\_of\_y=the\_word.indexOf("y");  
//location\_of\_y) 字母y 的位置) 是5 。  
varcheeky=the\_word.indexOf("q");  
//cheeky 值是-1 ，因为在单词“monkey” 中没有字母q 。

indexOf 更实用之处:  
varthe\_email=prompt("What’syouremailaddress?","");  
varthe\_at\_is\_at=the\_email.indexOf("@");  
if(the\_at\_is\_at==-1)  
{  
alert("Youloser,emailaddressesmust  
have@signsinthem.");  
}

这段代码询问用户的电子邮件地址，如果用户输入的电子邮件地址中不包含字符 则 提

示用户＂＠你输入的电子邮件地址无效，电子邮件的地址必须包含字符@ 。＂

3 、charAt  
chatAt 方法用于发现一个字符串中某个特定位置的字符。  
这里是一个例子：  
varthe\_word="monkey";  
varthe\_first\_letter=the\_word.charAt(0);  
varthe\_second\_letter=the\_word.charAt(1);  
varthe\_last\_letter=the\_word.charAt(the\_word.length-1);

the\_first\_letter( 第1 个字符) 是"m"  
the\_second\_letter( 第2 个字符) 是"o"  
the\_last\_letter( 最后一个字符) 是"y"

注意利用字符串的length( 长度) 属性你可以发现在包含多少个字符。在本例中，

the\_word 是"monkey" ，所以the\_word.length 是6 。不要忘记在一个字符串中第1 个字符的

位置是0 ，所以最后一个字符的位置就是length-1 。所以在最后一行中用了

the\_word.length-1 。&gt;&gt;

4 、子字符串（substring ）  
子字符串（substring ）和charAt 有些象，不同之处在于它能够从一个单词中抓取整个的

子字符串，而不只是字母，这里是其格式：

varthe\_substring=the\_string.substring(from,to);

"From" 指的是子字符串中第１个字母的位置，"to" 有点奇特，它是该子字符串中比最后

一个位置大１的位置．使用这种神奇的方法你可以标记子字符串的起始和结束位置，用

"to" 的位置减去"from" 的位置就会得出该子字符串的长度：

varthe\_string="monkey";  
varclergy=the\_string.substring(0,4);  
vartool=the\_string.substring(3,6);

运行该段代码后变量clergy 的值为"monk"; 变量tool 的值为"key" 。

子字符串常和indexOf 一起使用，将字符串分成若干块．例如，  
你可以从一个给定的URL 中抽取出其域名：

varthe\_url=prompt("What’stheURL?","");  
varlead\_slashes=the\_url.indexOf("//");  
vardomain\_start=lead\_slashes+2;  
varwithout\_resource=the\_url.substring(domain\_start,the\_url.length);  
varnext\_slash=without\_resource.indexOf("/");  
vardomain=without\_resource.substring(0,next\_slash);

这段代码的意思是：如果你输入  
"[http://www.webmonkey.com/javascript/index.html"](http://www.webmonkey.com/javascript/index.html%22) ; ，则域名就是

"www.webmonkey.com" ．如果这个方法对你来说有些麻烦，我将向你介绍如何使用split

方法简化其执行过程．但是首先我们作一些分析．

基本的技巧是将第１个斜杠和第２个斜杠之间的内容分离出来：  
varthe\_url=prompt("What’stheURL?","");  
// 这行代码向用户询问一个URL ．假设用户输入了  
"[http://www.webmonkey.com/javascript/index.html."](http://www.webmonkey.com/javascript/index.html.%22) ;  
varlead\_slashes=the\_url.indexOf("//");  
这行代码确定第一个双斜杠的位置．在本例中lead\_slashes 的值是５，因为双斜杠的位

置从５开始．

你可能会想，通常的URL 都是以http:// 开始，所以双斜杠的位置肯定是在５开始，为什

么还要加入indexOf 这一段多余的代码呢？但是问题的关键在于你不知道用户在填入URL

时是否一定填入http: ，他们也许会不小心多键入了一个空格，也许他们所键入的URL 在

一个加密服务器上，其URL 是"[https://www.whatever.com/"](https://www.whatever.com/%22) ; ．在编程你必须预料到种种

可能发生的问题．所以我们必须用indexOf 方法确定双斜杠的确切的起始位置．

**vardomain\_start=lead\_slashes+2;**

这行代码用于计算该域名的第１个字母的起始位置．由于这里有一个双斜杠，所以域名

第１个字母的起始位置应该在双斜杠所在位置加２的位置．

varwithout\_resource=the\_url.substring(domain\_start,the\_string.length);

这段代码将域名起始位置往后的所有字符都提取出来．所以执行完这行代码后

without\_resource 是"www.webmonkey.com/javascript/index.html."

varnext\_slash=without\_resource.indexOf("/");

这行代码计算出该字符串中下一个斜杠的位置，而从该字符串起始位置到这个斜杠之间

的内容就是域名．在本例中下一个斜杠的位置是17 。

vardomain=without\_resource.substring(0,next\_slash);

最后一步是提取出该字符串起始位置到下一个斜杠之间的所有内容．在本例中使得域名

等同于"www.webmonkey.com" 。

这样做确实很麻烦，利用split 方法则可以使该过程容易很多．&gt;&gt;

5 、分割方法(splittingmethod)  
你可以使用split 方法用限位器来分割一系列的名称，然后将其  
放在一个数组中．例如：

varmy\_friends="trixie,moxie,sven,guido,hermes";

varfriend\_array=my\_friends.split(",");

for(loop=0;loop&lt;friend\_array.length;loop++)  
{document.writeln(friend\_array\[loop]+"ismyfriend.&lt;br&gt;");}

这段代码将字符串my\_friends 分割成包含５个元素的数组．JavaScript 可以为你自动建

立一个数组，所以你无需使用newArray() ．

将字符串分割成数组之后，我们使用了循环语句写出每一个名称．我们可以利用split 方

法简化前面所讲到的域名提取：

varthe\_url=prompt("What’stheURL?","");  
varfirst\_split=the\_url.split("//");  
varwithout\_resource=first\_split\[1];  
varsecond\_split=without\_resource.split("/");  
vardomain=second\_split\[0];

这段代码简化了很多而且也更容易理解．我们来分析一些这段代码：

varthe\_url=prompt("What’stheURL?","");

提示用户输入一个URL ，假设用户输入  
"[http://www.webmonkey.com/javascript/index.html"](http://www.webmonkey.com/javascript/index.html%22) ; ．  
varfirst\_split=the\_url.split("//");  
将用户输入的字符串分割成两块：first\_split\[0] 是"http:" ，first\_split\[1] 是

"www.webmonkey.com/javascript/index.html."  
varwithout\_resource=first\_split\[1];  
// 提取出数组中的第２个元素，所以现在without\_resource 是

"www.webmonkey.com/javascript/index.html."  
varsecond\_split=without\_resource.split("/");  
将without\_resource 分割成３块：www.webmonkey.com,javascript, 和index.html ．现

在你可以看到split 的用途了吧？

vardomain=second\_split\[0];

现在我们提取出新数组中的第１个元素就可得出域名．