js 字符串方法小结

237 阅读1分钟

字符串其实方法不少,但是处理复杂的处理还是用着正则比较方便。

  • 无敌的relace+正则
var str = "1a2b3c"
var reg = /\d+/ig
var newStr = str.replace(reg,function(item){
    console.log(item)
    return ""
})
console.log(newStr)

替换字符串,返回替换完成的新字符串,不改变原来字符串,真的无敌。

  • charAt
var str = "1a2b3c"
var r = str.charAt(1)
console.log(r)

根据脚标查询字符

  • concat
var str = "1a2b3c"
var newStr = str.concat(2,4,["1"])
console.log(newStr,str)

字符串拼接,不改变原来字符串。

  • slice,substr,substring
var str = "abcdef"
var s1 = str.slice(2)
var s2 = str.substr(2)
var s3 = str.substring(2)
var s11 = str.slice(2,4)
var s22 = str.substr(2,4)
var s33 = str.substring(2,4)
var s4 = str.slice(-2)
var s5 = str.substr(-2)
var s6 = str.substring(-2)
var s44 = str.slice(2,-4)
var s55 = str.substr(2,-4)
var s66 = str.substring(2,-4)
console.log(s1,s2,s3,s11,s22,s33,s4,s5,s6,s44,s55,s66)  //cdef cdef cdef cd cdef cd ef ef abcdef   ab

都不改变源字符串

  • localeCompare
var str = "abc"
var str1 = "def"
var r = str.localeCompare(str1)
console.log(r) //大于返回1,等于返回0,小于返回-1

大于返回1,等于返回0,小于返回-1

  • fromCharCode
var str = String.fromCharCode(100,101,102)
console.log(str) 

没啥说的,根据code码返回字符串

  • toUpperCase,toLowerCase
var str = "abcde"
str.toUpperCase()
str.toLowerCase()

改变大小写,不改变源字符串