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

来源:互联网 发布:2017年淘宝销量排行榜 编辑:程序博客网 时间:2024/05/21 11:11

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">
2my_string= new String("Welcome to sharejs.com");
3</script>


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

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

1document.write(my_string.length);

输出: 23

给字符串加粗:

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


设置字符串的长度

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


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

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

设置字体为fixed

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


设置字符串字体颜色

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


设置字符串字体为斜体

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


给字符串添加链接

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


给字符串设置删除线

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


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

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


Making sub script

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