最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
JavaScript字符串对象(string)基本用法示例
时间:2017-02-06 编辑:简简单单 来源:一聚教程网
本文实例讲述了JavaScript字符串对象(string)基本用法。分享给大家供大家参考,具体如下:
1.获取字符串的长度:
代码如下 | 复制代码 |
vars ="Hello world"; document.write("length:"+s.length); |
2.为字符串添加各种样式,如:
代码如下 | 复制代码 |
vartxt ="Some words"; document.write(" Big: "+ txt.big() +" ")document.write(" Small: "+ txt.small() +" ")document.write(" Bold: "+ txt.bold() +" ")document.write(" Italic: "+ txt.italics() +" ")document.write(" Blink: "+ txt.blink() +" (does not work in IE) ")document.write(" Fixed: "+ txt.fixed() +" ")document.write(" Strike: "+ txt.strike() +" ")document.write(" Fontcolor: "+ txt.fontcolor("Red") +" ")document.write(" Fontsize: "+ txt.fontsize(16) +" ")document.write(" Link: "+ txt.link("http://www.jb51.net") +" ") |
3.获取字符串中部分内容首次出现的位置:
代码如下 | 复制代码 |
varhw_text ="Hello world"; document.write(hw_text.indexOf("Hello")+" document.write(hw_text.indexOf("world")+" document.write(hw_text.indexOf("abc")+" |
4.内容替换:
代码如下 | 复制代码 |
varstr="Visit Microsoft!" document.write(str.replace(/Microsoft/,"W3School")) |
效果图:
示例代码:
代码如下 | 复制代码 |
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
body {background-color:#e6e6e6}
(一)length属性:获取字符串的长度
Hello world, Hello javascript!
vars = document.getElementById("hw").innerHTML; document.write("length:"+s.length);
(二)为字符串添加样式
对字符串调用样式的相关方法时,会自动拼接相应的html标签
some words
vartxt = document.getElementById("hw_02").innerHTML; document.write(" Big: "+ txt.big() +" ")document.write(" Small: "+ txt.small() +" ")document.write(" Bold: "+ txt.bold() +" ")document.write(" Italic: "+ txt.italics() +" ")document.write(" Blink: "+ txt.blink() +" (does not work in IE) ")document.write(" Fixed: "+ txt.fixed() +" ")document.write(" Strike: "+ txt.strike() +" ")document.write(" Fontcolor: "+ txt.fontcolor("Red") +" ")document.write(" Fontsize: "+ txt.fontsize(16) +" ")document.write(" Link: "+ txt.link("http://www.jb51.net") +" ")functionalertBig(){ alert(txt.big()); }
(三)indexOf方法:定位字符串中某一个指定的字符首次出现的位置
varhw_text ="Hello world"; document.write(hw_text.indexOf("Hello")+" document.write(hw_text.indexOf("world")+" document.write(hw_text.indexOf("abc")+"
(四)replace()方法:替换字符串中的部分内容
varstr="Visit Microsoft!" document.write(str.replace(/Microsoft/,"jb51"))
|
相关文章
- JavaScript实现替换字符串中最后一个字符的方法 06-02
- Javascript 中字符串方法总结 08-17
- javascript 下常用的字符串操作 08-09
- Javascript实现Heredoc语法 及大量字符串拼接实现 01-20
- 不用 eval 的方式通过字符串调用 JavaScript 的方法 10-08
- javascript计算字符串中每个字符出现次数 04-03