您好,欢迎来到意榕旅游网。
搜索
您的当前位置:首页JavaScript 截取字符串代码实例

JavaScript 截取字符串代码实例

来源:意榕旅游网

这篇文章主要介绍了JavaScript 截取字符串代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

代码如下

<script>
 $(document).ready(function () {
 //下标从0开始
 let str = '1234567';
 //使用一个参数
 console.log(str.slice(3)) //从第4个字符开始,截取到最后个字符;返回"4567"
 console.log(str.substring(3)) //从第4个字符开始,截取到最后个字符;返回"4567"
 //使用两个参数
 console.log(str.slice(1, 5)) //从第2个字符开始,到第5个字符;返回"2345"
 console.log(str.substring(1, 5)) //从第2个字符开始,到第5个字符;返回"2345"
 //如果只用一个参数并且为0的话,那么返回整个参数
 console.log(str.slice(0))
 console.log(str.substring(0))
 //返回第一个字符
 console.log(str.slice(0, 1)) //1
 console.log(str.substring(0, 1)) //1
 //在上面的例子中我们可以看出slice()和substring()的用法是相同的
 //返回的值也是一样的,但当参数为负数时,他们的返回值却不一样,看下面的例子
 console.log(str.slice(2, -5)) // 34
 console.log(str.substring(2, -5)) // 12
 //从上面两个例子可以看出slice(2,-5)实际上是slice(2,4)
 //负5加上字符串长度9转换成正4(若第一位数字等于或大于第二位数字,则返回空字符串);
 //而substring(2,-5)实际上是substring(2,0),负数转换为0,substring总是把较小的数作为起始位置。
 //substring和substr的区别
 //相同点:如果只是写一个参数,两者的作用都一样:都是是截取字符串从当前下标以后直到字符串最后的字符串片段。
 let str2 = '1234567';
 console.log(str2.substr(2)); // "34567"
 console.log(str2.substring(2)); // "34567"
 //不同点:第二个参数
 //substr(startIndex,lenth): 第二个参数是截取字符串的长度(从起始点截取某个长度的字符串);
 //substring(startIndex, endIndex): 第二个参数是截取字符串最终的下标 (截取2个位置之间的字符串,‘含头不含尾')。
 console.log("1234567".substr(2, 5)); // "34567" 从下标2开始,截取5个
 console.log("1234567".substring(2, 5)); // "345" 从下标2开始,截取到下标为5的长度
 //总结:String.substr(startIndex,lenth) 这个是我们常用的从指定的位置(startIndex)截取指定长度(lenth)的字符串; 
 //String.substring(startIndex, endIndex) 这个是startIndex,endIndex里找出一个较小的值,然后从字符串的开始位置算起,截取较小值位置和较大值位置之间的字符串,截取出来的字符串的长度为较大值与较小值之间的差。
 // 函数:split() 
 //功能:使用一个指定的分隔符把一个字符串分割存储到数组
 let str3 = '1,2,3,4,5,6';
 let arr = str3.split(',');
 console.log(arr); //["1", "2", "3", "4", "5", "6"]
 // 函数:John() 
 // 功能:使用您选择的分隔符将一个数组合并为一个字符串
 let myList = new Array('jpg', 'bmp', 'gif', 'ico', 'png');
 let portableList = myList.join('|');
 console.log(portableList); //jpg|bmp|gif|ico|png 
 })
 </script>

Copyright © 2019- yrrf.cn 版权所有 赣ICP备2024042794号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务