js操作字符串总结

js操作字符串总结

charAt() charCodeAt()

charAt() 返回选中的字符 charCodeAt() 返回选中的字符编码。 都只接受一个参数。
var str="hello world";
console.log(str.charAt(1)) // e
console.log(str.charCodeAt(1)) // 101

concat()

concat() 可以接受多个参数,实践中我们一般使用 +
var str="hello";
var hel="world";
console.log(str.concat(hel,"xxxx"));//  helloworldxxxx

slice() substring() substr()

slice() 接收2个参数,第一个代表开始位置,第2个代表结束位置(实际上算结束位置前一个/包含头不包含尾。
substring() 接收2个参数,第一个代表开始位置,第2个代表字符串前面一个的位置
substr() 接收2个参数,第一个代表开始位置,第2个代表返回字符的个数。
一个参数表示开始位置到结尾。
var  str="helloworld";
console.log(str.slice(3)) //loworld
console.log(str.slice(3,7)) // lowo
console.log(str.substring(3))//loworld
console.log(str.substring(3,7))//lowo
console.log(str.substr(3))//loworld
console.log(str.substr(3,7)) // loworld  6(6代表返回字符的个数)
console.log(str.slice(3,-4));low
 console.log(str.substring(3,-4));	第2个参数小于等于0都= str.string(3,0); 
 但是由于此方法会按照参数大小作为开始结束位置,由此又变成了 str.substring(0,3) //hel
  console.log(str.substr(3,-4));// 第2个参数 小于等于0 返回的都是 空字符串

indexOf() lastIndexOf()

2个方法都是从搜索,indexOf()从开头向后找,找到就返回,lastIndexOf()正好相反,找不到返回-1。
都可以接受2个参数,要查找的字符串和位置
var str="helloworld";
console.log(str.indexOf("zzz")) ; // -1
console.log(str.indexOf("h")) //0
console.log(str.lastIndexOf("h"))//0

trim()

trim() 删除字符串前后的空格(不包括字符串间的空格)
var str=" hello world   ";
console.log(str.trim())//helloworld

toLowerCase() toUpwerCase()

toLowerCase() 转化为小写   toUpwerCase() 转化为大写
var str="helloworld"; var sht="HELLOWORLD"
console.log(sht.toLowerCase())//helloworld
console.log(str.toUpwerCase())//HELLOWORLD

replace()

replace() 可接收2个参数,第一个代表要替换的字符串(或者正则),第二个代表替换的内容
var str="helloworld";
console.log(str.replace("hello","xzz"))//xzzworld
console.log(str.replace(/hello/g,"xzz"))//xzzworld

match()

match() 返回指定的值
var str="helloworld";var str1="1 plus 2 equal 3"
console.log(str.match("hello"))//	hello
console.log(str1.match(/\d+/g))//	1,2,3

split()

split()将字符串转化为数组
var str="helloworld";
console.log(str.split("")); //['h','e','l','l','o','w','o','r','l','d'];

fromCharCode()

fromCharCode()接收一或多个字符编码,然后将其转换为字符串 
fromCharCode方法是String构造函数的一个静态方法 
console.log(String.fromCharCode(104,101,108,108,111));//hello

localeCompare()

这个方法用于比较两个字符串 
1.如果字符串在字母表中应该排在字符串参数之前,则返回一个负数 
1.如果字符串等于字符串参数,则返回0 
1.如果字符串在字母表中应该排在字符串参数之后,则返回一个正数 
   
var str="yellow"; 
console.log(str.localeCompare("brick"));//1 
console.log(str.localeCompare("yellow"));//0 
console.log(str.localeCompare("zoo"));//-1 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值