Web 前端开发 前端开发那些事让前端飞

JavaScript中关于字符串操作总结

2017-08-26  本文已影响0人  FeRookie

因为关于JavaScript中的字符串(String类型)的操作经常是忘记或者是混淆了,所以今天借着这个机会进行总结一番。

String类型都有valueOf(),toLocaleString(),toString()方法,都返回对象所表示的基本字符串。String类型都有一个length属性,表示字符串的长度

1. 字符方法
var str = 'hello world'
console.log(str.charAt(1)) //e

charCodeAt()返回的是该位置的字符串编码

var str = 'hello world'
console.log(str.charCodeAt(1)) //101

TIP: charCodeAt和charAt中如果传入的参数为负数或者大于该字符串的长度,charAt()返回的是空字符(""),charCodeAt()返回的是NAN。

2. 字符串操作方法
var str = 'hello '
var res = str.concat('world', '!')
console.log(res) //hello world
console.log(str) //hello

TIP: concat中传入的参数如果是非字符串,则会先调用toString方法尝试转换成字符串然后进行拼接

slice()方法会将传入的负值与字符串的长度相加。substr()方法将负的第一个参数加上字符串的长度,而负的第二个参数转为0。substring()会将所有负值参数都转换为0,如果第二个参数比第一个大的话,那么会将两个参数位置进行交换

var str = 'hello world'
str.slice(3) // 'lo world'
str.substring(3) // 'lo world'
str.substr(3) // 'lo world'
str.slice(3, 7) //'lo w'
str.substring(3, 7) //'lo w'
str.substring(3, 7) //'lo worl'

var str = 'hello world'
str.slice(-3) //'rld' 从后往前数
str.substring(-3) //'hello world',会转为0,然后截取到最后就返回整个字符串了
str.substr(-3) //'rld',第一个参数从后往前数
str.slice(3, -4)// 'lo w',若第二个参数小于第一个参数,则返回空字符串
str.substring(3, -4) //'hel', 负数会转为0,然后交换0和3的位置
str.substr(3, -4) // ""会将负数转为0,然后如果第二个小于第一个则会返回空字符串 
3. 字符串位置方法
var str = 'hello world'
console.log(str.indexOf('o')) //4
console.log(str.lastIndexOf('o')) //7

indexOf()和lastIndexOf()还可以接受第二个参数表示从第几位进行搜索。

var str = '   hello world  '
console.log(str.trim()) //'hello world'
var str = 'cat, bat, sat, fat'
var pattern = /.at/
var matches = str.match(pattern)
console.log(matches.index) //0
console.log(matches[0]) //'cat'
console.log(pattern.lastIndex) // 0

如上,match()方法返回一个数组。

var test = 'cat, bat, sat, fat'
var pos = test.search(/at/)
console.log(pos) // 1
var text = 'cat, bat, sat, fat'
var res = text.replace('at', 'ond')
console.log(res) // 'cond, bat, sat, fat'
res = text.replace(/at/g, ''ond")
console.log(res) // "cond, bond, sond, fond"
String.fromCharCode(104, 101, 108, 108, 111) //hello

以上就是关于JavaScript中字符串的一些基本操作。

上一篇 下一篇

猜你喜欢

热点阅读