网络编程 
首页 > 网络编程 > 浏览文章

javascript学习笔记(三) String 字符串类型介绍

(编辑:jimmy 日期: 2025/12/25 浏览:3 次 )
1.字符方法charAt() 、charCodeAt()、fromCharCode()
复制代码 代码如下:
var stringValue = "hello world";
alert(stringValue.charAt(1));    //"e"
alert(stringValue[1]);      //"e"
alert(stringValue.charCodeAt(1));  //101
alert(String.fromCharCode(104,101)); //"he"

2.返回子字符串方法slice()、substr()、substring()
slice()、substring()方法第一个参数指定子字符串的起始位置,第二个参数指定结算位置(不包括结束位置),原字符串不变
substr()第二个参数指的是返回的字符个数,原字符串不变
复制代码 代码如下:
var stringValue = "hello world";
alert(stringValue.slice(3)); //"lo world"
alert(stringValue.substring(3)); //"lo world"
alert(stringValue.substr(3)); //"lo world"
alert(stringValue.slice(3,7)); //"lo w"
alert(stringValue.subtring(3,7));   //"lo w"
alert(stringValue.substr(3,7)); //"lo worl"

alert(stringValue.slice(-3)); //"rld",取数组最后3个字符
alert(stringValue.slice(-3)); //"rld",取数组最后3个字符

3.字符串位置方法 indexOf() 和 lastIndexOf()
indexOf()方法从前向后搜索子字符串,可接收一个参数或两个参数,第一参数指定要搜索的子字符串,第二个参数指定从该位置向后搜索,没找到返回-1
lastIndexOf()方法从后向前搜索子字符串,可接收一个参数或两个参数,第一参数指定要搜索的子字符串,第二个参数指定从该位置向前搜索,没找到返回-1
复制代码 代码如下:
var stringValue = "hello world";
alert(stringValue.indexOf("o")); //4
alert(stringValue.lastIndexOf("o")); //7
alert(stringValue.indexOf("o",6)); //7
alert(stringValue.lastIndexOf("o",6)); //4

4.字符串大小写转换方法 toLowerCase()和toUpperCase()
toLowerCase()转换为小写,toUpperCase()转换为大写

5.字符串的比较localeCompare()
localeCompare()可以比较英文,也可以比较中文,大写字母在前小写字母在后

6.字符串排序:
复制代码 代码如下:
var stringValue= ["中国","楠楠","俊俊"];
alert(stringValue.sort(stringCompare));
//升序排序函数a-z
function stringCompare(value1,value2) {
return value1.localeCompare(value2); //降序z-a,value1和value2互换位置
}
上一篇:javascript学习笔记(四) Number 数字类型
下一篇:javascript学习笔记(二) js一些基本概念
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 网站地图 SiteMap