1-字符串操作

202 阅读2分钟

字符串

var str = 'css样式设置不换行white-space:nowrap;自动换行word-wrap:wrap;word-break:nomal' 
1.字符截取方法:
str.slice(start,end) 
str.substring(start,end('可选'))
str.substr(start,length('可选'))

slice(start,end)方法


// 倒着截取
str.slice(-8) 
// 倒着截取从右向左,end此时为字符串末尾下标,可以不写 
// 当end为负数时等同于(0,length-1) str.slice(0,-1) 
// css样式设置不换行white-space:nowrap;自动换行word-wrap:wrap;word-break:nom 

substring(start,end)


str.substring(7,4) 
 // 与slice不同的是不能写负数,截取结束位置不包括end,实际为end-1;end不写,截取长度到字符串末尾
 // str.substring(7,4)始终以最小的下标作为起始下标等同(4,7) str.substring(0) 
 
控制台打印// css样式设置不换行white-space:nowrap;自动换行word-wrap:wrap;word-break:nomal 

str.substr(start,length)

 //从指定位置开始,截取指定长度的字符串 
 str.substr(0,7)
 // css样式设置
2. 字符串查找替换
str.replace(old,new) // 替换
str.split(font) // 切割为数组

str.charAt(4) // 查找指定下标的字符

str.indexOf('需要查找的字符')  // 获取字符下标
str.lastIndexOf('查找字符出现的末尾位置')

str.cancat('拼接到后面的字符')  // 字符串拼接

 str.localeCompare(String)  // 比较字符大小

str.replace(old,new)

 str.replace(old,new)
 //查找出指定内容并替换,不改变原字符串,返回的是一个新的字符串 
 str.replace('css样式','')   // '设置不换行white-space:nowrap;自动换行word-wrap:wrap;word-break:nomal'

str.split(font)

 // 字符串切割为数组
  str.split(font)  // font为切割符

str.charAt(index)

 str.charAt(4) // 返回下标为4处的字符

str.indexOf('需要查找的字符')

str.indexOf('css') // 返回指定字符的下标
// 也是返回字符第一次出现的下标

str.lastIndexOf('查找字符出现的末尾位置')

 str.lastIndexOf('css') // 与indexOf一样,从字符串末尾位置开始查找

str.cancat('拼接到后面的字符')

str.cancat('拼接到后面的字符')
// 效果等同使用‘+’

str.localeCompare(String)

str.localeCompare('字符') 
// 按照Unicode编码来比较两个字符串的大小 返回值是-1,0,1