您的位置:首页 > Web前端 > JavaScript

javascript字符串对象的常用属性和方法

2014-03-26 10:39 846 查看
javascript的string对象提供了很多属性和方法用来控制字符串的操作和风格显示.下面将通过几个范例了解javascript string对象的操作方式

对String的各种操作,其中

document.write("<p align=\"center\">"); // 输出HTML标签“<p>”,并设置居中对齐

是对下面要输出的string的格式设置,如果不改变的话,将会把这种格式(居中对齐)应用到以后所有的document.write()。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript">
var comment = "静夜思李白床前明月光,疑是地上霜。举头望明月,低头思故乡。"; // 诗的内容
var partial = comment.substring(0, 3); // 取出标题
partial = partial.bold(); // 标题加粗
document.write("<p align=\"center\">"); // 输出HTML标签“<p>”,并设置居中对齐
document.write(partial); // 输出标题
partial = comment.slice(3, 5); // 取出作者
document.write("<br>"); // 输出换行标签<br>
document.write(partial); // 输出作者
partial = comment.slice(5, 17); // 取出第一句诗文
partial = partial.fontcolor("gray"); // 设置颜色为gray(灰色)
document.write("<br>"); // 输出换行标签
document.write(partial); // 输出诗句
partial = comment.slice(17, 29); // 取出第二句诗文
partial = partial.fontcolor("gray"); // 设置颜色为gray(灰色)
document.write("<br>"); // 输出换行标签
document.write(partial); // 输出诗句
document.write("</p>"); // 输出HTML标签“<p>”的结束标签

document.write("<br/>");
var content = "静夜思李白床前明月光,疑是地上霜。举头望明月,低头思故乡。"; // 诗的内容
var part = content.substring(0, 3);
part.bold();
document.write("<p align=\"center\">");
document.write(part);
document.write("<br/>");
part = content.slice(3, 5);
part=part.fontcolor("blue");
document.write(part)

</script>
</head>

<body>
</body>
</html>



JavaScript string 对象

javascript的string对象提供了很多属性和方法用来控制字符串的操作和风格显示.下面将通过几个范例了解javascript string对象的操作方式

首先声明一个字符串(string)对象

1
<script
type=
"text/javascript"
>
2
my_string= 
new
 
String(
"Welcome
to sharejs.com"
);
3
</script>




Length 属性用来获取字符串的长度

下面的方法返回my_string 的完整长度,包括空格

1
document.write(my_string.length);


输出: 23


给字符串加粗:

1
document.write(my_string.bold());


设置字符串的长度

1
document.write(my_string.fontsize(6));


设置字符串闪烁( 不适用于 IE )

1
document.write(my_string.blink());


设置字体为fixed

1
document.write(my_string.fixed());


设置字符串字体颜色

1
document.write(my_string.fontcolor(
"blue"
));


设置字符串字体为斜体

1
document.write(my_string.italics());


给字符串添加链接

1
document.write(my_string.link(
"http://www.sharejs.com"
));


给字符串设置删除线

1
document.write(my_string.strike());


根据开始和结束位置返回子字符串

1
document.write(my_string.substring(10,15));


Making sub script

1
document.write(my_string.sub());

                                                                       
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: