js常用字符串方法

concat()

将两个字符或者多个字符的组合起来返回一个新字符串

     let str = "Hello world!";
     str.concat("boy")//"Hello world!boy"
     str.concat("boy","boy",123)//"Hello world!boyboy123"
indexOf(value,startIndex)

从下标0开始检索,返回第一个匹配的下标。没有返回-1

     let str = "Hello world!";
     str.indexOf("e")//1

如果给第二个参数表示从startIndex开始检索,返回在原字符串第一次出现的位置下标

     let str = "Hello world!";
     str.indexOf("o",4)//4,
lastIndexOf和indexOf相反(检索方向从末尾到起点)

返回下标还是从左开始

     let str = "Hello world!";
     str.lastIndexOf("o",4)//4,从index==4,往前检索
substring(start,end)

返回字符串的一个子串,从起始位置截取到结束位置(不包含结束位置)。

     let str = "Hello world!";
     str.substring(1,8)//ello wo
substr(start,length)

返回字符串的一个子串,从起始位置截取相应长度。

     let str = "Hello world!";
     str.substr(1,8)//ello wor

上述两种方法如果长度不够,不会在截取

split(“分隔符”)

通过分隔符,将字符串拆分为数组

     let str = "Hello world!";
     str.split(" ")// ["Hello", "world!"]
     str.split("e")// ["H", "llo world!"]
replace(reg,str)

用来查找匹配一个正则表达式的字符串,然后使用新字符串代替匹配的字符串。

     let str = "Hello world!";
     str.replace(/l/,"o")//"Heolo world!",只会替换第一个,不会替换全局
     str.replace(/l/g,"o")//"Heooo worod!"正则表达式,g匹配全局
toUpperCase() 、toLowerCase() 字符串大小写转换
let str="Hello world!"; 
console.log(str.toLowerCase()); //hello world! 
console.log(str.toUpperCase()); //HELLO WORLD!

ES6新增常用字符串方法

includes()

返回布尔值,表示是否找到了参数字符串。

     let str = "Hello world!";
     str.includes('o') // true
startsWith()

返回布尔值,表示参数字符串是否在原字符串的头部。

     let str = "Hello world!";
     str.startsWith('Hello') // true
endsWith()

返回布尔值,表示参数字符串是否在原字符串的尾部。

     let str = "Hello world!";
     str.endsWith('world!') // true
includes() ,tartsWith(),endsWith() 三个方法都支持第二个参数,表示开始搜索的位置。
		let str = "Hello world!";
        str.startsWith('world', 6) // true
        str.endsWith('Hello', 5) // true
        str.includes('Hello', 6) // false

上面代码表示,使用第二个参数n时,第n个位置开始直到字符串结束。
endsWith()的行为与其他两个方法有所不同,从后往前数。

repeat()

返回一个新字符串,表示将原字符串重复n次

		let str = "Hello world!";
        str.repeat(2) //"Hello world!Hello world!"

字符串补全长度的功能 padStart()、padEnd()

padStart()字符串不够指定长度,会在头部补充
		let str = "hello"
        str.padStart(10,"boy")//boybohello,注意补充后长度不够时候,会循环
padEnd()字符串不够指定长度,会在尾部补充
		let str = "hello"
        str.padEnd(10,"boy")//helloboybo,注意补充后长度不够时候,会循环

上述两种方法,如果省略所需填充的字符串,一律填充空格
echarts中让纵坐标文字对齐,可以试下这两个方法
比如你的数据像这种:
张三 12
李四 9
何老怪 23

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值