字符串中常用的方法

xiaoxiao2021-02-28  97

1.length

var str = "hello world"; console.log(str.length);//所有的空格都算//15

2.prototype(原型)

String.propotype.strim=function(str){ return this.replace("/(^\s*|\s*$)/","") } var str=" hello world str.strim(str)//hello world

3.charAt(),charCodeAt()

charAt()查找字符串的位置
var str="a1b2c3"; str.charAt(2)//b
charCodeAt()
str.charCodeAt(e); 97

4.indexOf/lastIndexOf 查找索引

这两个方法都可以接受两个参数(i,index) i:要查找的参数,index从哪个索引开始查找

lastIndexOf()是倒过来查找,找到是最开始的位置

var str="hello world"; console.log(str.indexOf("o"));//5 console.log(str.lastIndexOf("o")); //7

5.字符串的截取

substr(startIndex,length);startIndex:开始的索引;length:截取总个数 var str="hello world"; console.log(str.substr(0,4));//hell console.log(str.substr(0));//hello world substring(startIndex,endIndex)\slice(startIndex,endIndex)两者唯一的区别就是slice可以接受负数而且截取的时候 不包含lastIndex值; console.log(str.substring(0,4));//hell console.log(str.substring(0));//hello world console.log(str.substring());//hello world console.log(str.slice());//hello world console.log(str.slice(0));//hello world console.log(str.slice(0,4));//hello world

6.大写小转换(toLowerCase()/toUpperCase())

7.replace(newStr,oldStr)替换 old替换new(后者替换前者)

var old="HELLO WORLD"; //console.log(str.replace(str,old)) //console.log(str.replace(/o/g,"a"));//返回的是字符串;

8.split(拆分符号) 将字符串转换为数组

var str="hello world" console.log(str.split(""));//["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]

9.match() ;比较特殊

var str2="a1b2c3" console.log(str2.match("1"));// ["1", index: 0, input: "1a2b3c4d5e"] console.log(str2.match(/\d+/g));// ["1", "2", "3", "4", "5"] var str = '?keyword=1&value=haha'; var reg = new RegExp("(^|&)" + "keyword" + "=([^&]*)(&|$)"); var result =str.substr(1);//keyword=1&value=haha console.log(result.match(reg));//["keyword=1&", "", "1", "&", index: 0, input: "keyword=1&value=haha"]
转载请注明原文地址: https://www.6miu.com/read-81455.html

最新回复(0)