<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>查找类字符串方法</title>
</head>
<body>
<script>
/*
①字面量字符串, 所见即所得
比如:my_str = "I love you!"
②字符串对象 => 类数组,和数组长得非常的像,但是并不是数组,因为并不具备有数组的所有方法
*/
var str1 = "I love you!";
console.log(typeof str1); //打印:string
console.log(str1[0]); //打印:I
var str2 = new String("I love you!");
var arr1 = ["I","love","you!"];
console.log(typeof str2); //打印:object
console.log(str2[0]); //打印:I
console.dir(str2);
console.dir(arr1);
/*
通过str[index] 这样的方式取值,是有兼容问题的,IE8以下是无法使用的,charAt没有这样的问题
str.charAt(index)
- index:字符串的索引值(下标),如果说不填,默认为0
- 如果超出str.length,或者小于0,那么会返回一个空字符串
*/
console.log(str1.charAt(0)); //打印:I
console.log(str1.charAt(str1.length+5)); //打印:空
console.log(str1.charAt(-5)); //打印:空
/*
str.charCodeAt(index) 用于获取当前字符串的unicode编码
- index :字符串的索引值(下标),如果不给,默认为0
- 如果下标不存在的值,那么会返回给你一个NaN
如果比较字符串,比较的是Unicode编码的大小
*/
var str3 = "我爱你!";
var str4 = "我喜欢你!"
console.log(str3.charCodeAt()); //打印:25105
console.log(str3.charCodeAt(1)); //打印:29233
console.log(str3.charCodeAt(-10)); //打印:NaN
console.log(str3 > str4); //打印:true
//String.fromCharCode()
var arr2 = []
for(var i=0;i<str3.length;i++){
arr2[i] = str3.charCodeAt(i);
}
console.log(arr2); //打印:[25105, 29233, 20320, 65281]
console.log(String.fromCharCode(arr2[0], arr2[1], arr2[2],arr2[3])); //打印:我爱你
console.log(String.fromCharCode(...arr2)); //打印:我爱你
/*
str.indexOf(searchValue[,fromIndex])
可以用于查找str中是否有对应的字符串,如果有,返回该字符串第一次出现时候对应的索引值
-searchValue 当前想要查找的值
**如果说,查找的值,不存在,返回一个-1!!
fromIndex -这个值是一个可选值,从某个位置开始查找,不填默认为0
如果输入的值小于0,会当做0进行处理
如果说超出了索引值的范围,这时候会返回-1
*/
console.log(str1.indexOf('I')); //打印:0
console.log(str1.indexOf('lo')); //打印:2
console.log(str1.indexOf('lv')); //打印:-1
console.log(str1.indexOf('o')); //打印:3
console.log(str1.indexOf('o',4)); //打印:8
console.log(str1.indexOf('o', -1)); //打印:3
console.log(str1.indexOf('o', 50)); //打印:-1
/*
lastIndexOf
- searchValue
需要查找的字符串
- formIndex
起始搜索的位置(从后往前),如果不给,默认为str.length
如果超过str.length,则为str.length
如果小于0,则默认为0
如果说找不到指定的值,则返回-1;
用于返回查找指定值对应的最后一个索引索引,从后往前搜索
*/
console.log(str1.lastIndexOf("o")); //打印:8
console.log(str1.lastIndexOf("o", str1.length)); //打印:8
console.log(str1.lastIndexOf("o", -50)); //打印:-1
console.log(str1.lastIndexOf("lo")); //打印:2
</script>
</body>
</html>
JS查找类字符串方法
猜你喜欢
转载自blog.csdn.net/caoxinjian423/article/details/113757274
今日推荐
周排行