js字符串方法

charAt()

// 根據索引查找一個字符
    var str = 'abcde'
    console.log(str.charAt(1)) // 'b'

// 查找一個不存在的字符
    console.log(str.charAt(20)) // ""
    console.log(str[20]) // undefined
複製代碼

charCodeAt()

var str = '1'
    console.log(str.charCodeAt(0)) // 49
    '李'.charCodeAt(0) // 26446
    `根據索引值返回相應位置字符的編碼`
複製代碼

indexOf()

var str = 'JavaScript'
    console.log(str.indexOf('a', 2)) // 3
    `在字符串中 從索引2這個字符開始查找 a的索引`
複製代碼

match()

var str = 'hello 2019 byebye 2018'
    console.log(str.match(/\d+/g)) // ["2019", "2018"]
    `利用正則/\d+/g 將字符串中的 全部 多位數 以數組的形式查找出來`
複製代碼

replace()

var str = 'hello world!'
    console.log(str.replace('l', 'u')) // "heulo world!"
    `默認狀況下 只能替換第一個找到的字符`
    console.log(str.replace(/l/g, 9)) // he99o wor9d!
    `把全局l用9替換`
複製代碼

substr()

var str = 'helloworld!'
    console.log(str.substr(2, 4)) // "llow"
    `從索引2開始截取4個字符`
複製代碼

substring()

console.log(str.substring(1, 5))
    `從索引1截取到索引5這個位置 不包含索引5這一項`
複製代碼

split()

var str2 = 'a1b2c3d'
    str2.split(/\d/)
    `支持正則 \d 表明就是0-9中的一個數組`
複製代碼

toUpperCase() && toLowerCase()

var str = 'hello world'
    console.log(str.toUpperCase()) // "HELLO WORLD"
    var str = "HELLO WORLD"
    console.log(str.toLowerCase()) // "hello world"
複製代碼
相關文章
相關標籤/搜索