JS_字符串操作

<script>
    var str = 'hello world'
    // 获取字符串的长度
    console.log(str.length)
    // 获取下标为1的字符
    console.log(str.charAt(1))
    // 获取下标为1的字符的对应的编码
    console.log(str.charCodeAt(1))
    // 将wdc和yhf拼接在字符串的后面
    console.log(str.concat('wdc','yhf'))
</script>

结果:

 

 

<script>
    var str = 'hello world'
    // 从前往后查找字符‘o’
    console.log(str.indexOf('o'))
    // 从后往前查找字符‘o’
    console.log(str.lastIndexOf('o'))
    // 从下标6往后查找字符‘o’
    console.log(str.indexOf('o',6))
    // 从下标6往前查找字符‘o’
    console.log(str.lastIndexOf('o',6))

    var wdc = '    hollo world   '
    console.log(wdc)
    // 清除字符串前后的空格
    console.log(wdc.trim())

    var yhf = 'Hello Wdc'
    // 转换为小写字母
    console.log(yhf.toLowerCase())
    // 转换为大写字母
    console.log(yhf.toUpperCase())
</script>

结果;

 应用:查找当前字符串中的所有位置

<script>
    var str = 'Blog garden was founded in January 2004, blog garden was born in yangzhou, jiangsu province, such a very backward IT small city, although the city is small, but there are a lot of innovative people, blog garden was born for such a simple reason.'
    var arr = []
    var pos = str.indexOf('o')
    while(pos > -1){
        arr.push(pos)
        pos = str.indexOf('o', pos + 1)
    }
    console.log(arr)
</script>

结果:

 

posted @ 2020-04-06 22:05  手可摘星辰。  阅读(164)  评论(0编辑  收藏  举报