javascript 字符串处理全攻略(转)
javascript 字符串处理
一、声明字符串:
var normal_monkey = "I am a monkey!<br>";
document.writeln("Normal monkey " + normal_monkey);
var bold_monkey = normal_monkey.bold();
document.writeln("Bold monkey " + bold_monkey);
这里的声明: var bold_monkey = normal_monkey.bold();
和下面对声明是等同的:
var bold_monkey = "<b>" + normal_monkey + "</b>";
第1个版本的声明看起来要简明得多。这里用到了字符串对象中
的bold对象,其他的字符串对象还有indexOf, charAt,
substring, 以及split, 这些方法可以深入字符串的组成结构。
首先我们研究一下indexOf。
2、indexOf
indexOf用于发现一系列的字符在一个字符串中等位置并告诉你子字符串的起始位置。如
果一个字符串中部包含该子字符串则indexOf返回returns "-1."
例子:
var the_word = "monkey";
//让我们从单词 "monkey"开始。
var location_of_m = the_word.indexOf("m");
//location_of_m(字母m的位置)将为0,因为字母m位于该字符串的起始位置。
var location_of_o = the_word.indexOf("o");
//location_of_o(字母o的位置)将为1。
var location_of_key = the_word.indexOf("key");
//location_of_key(key的位置)将为3因为子字符串“key”以字母k开始,而k
在单词monkey中的位置是3。
var location_of_y = the_word.indexOf("y");
//location_of_y)字母y的位置)是5。
var cheeky = the_word.indexOf("q");
//cheeky值是-1,因为在单词“monkey”中没有字母q。
indexOf更实用之处:
var the_email = prompt("What’s your email address?", "");
var the_at_is_at = the_email.indexOf("@");
if (the_at_is_at == -1)
{
alert("You loser, email addresses must
ha
相关文档:
constructor属性始终指向创建当前对象的构造函数。比如下面例子:
// 等价于 var foo = new Array(1, 56, 34, 12);
var arr = [
1
,
56
,
34
,
12
];
console.log(arr.constructor === Array); ......
<!--
@page { margin: 2cm }
P { margin-bottom: 0.21cm }
-->
闭包(
closure
)
闭包意味着内层的函数可以引用存在于包围他的函数内的变量,即使外层函数的执行已经终止。这个特性非常强大和复杂。
例如:闭包如何使代码更清晰的两个例子
找出
ID
为‘
main’
的元素
var
......
倒计时计算
<body>
<div id="countdown"></div>
<mce:script type="text/javascript"><!--
var i = 0;
(function(){
var hour, min, sec, text;
tmp = 12 * 60 * 60 - i;
hour = Math.floor(tmp / 3600);
tm ......
/*
* 用来遍历指定对象所有的属性名称和值
* obj 需要遍历的对象
* author: Jet Mah
* website: http://www.javatang.com/archives/2006/09/13/442864.html
*/
function allPrpos(obj) {
// 用来保存所有的属性名称和值
var props = "";
&nbs ......
1. document.write( " "); 输出语句
2.JS中的注释为//
3.传统的HTML文档顺序是:document- >html- >(head,body)
4.一个浏览器窗口中的DOM顺序是:window- >(navigator,screen,history,location,document)
5.得到表单中元素的名称和值:document.getElementById( "表单中元素的ID號 &quo ......