JavaScript 字符串操作

concat方法
concat方法可用於拼接字符串

let a = "hello"
let b = a.concat(" world")
console.log(b)
//"hello world"

slice方法
slice方法:第一個參數指定子字符串開始位置,第二個參數表示子字符串最後一個字符後面的位置

let a = "hello world"
let a.slice(2, 3)
//"l"
let b = a.slice(2, 4)
//"ll"
let b = a.slice(2, 6)
//"llo "
let b = a.slice(2, 7)
//"llo w"

substr方法
substr方法: 第一個參數指定子字符串開始位置,第二個參數表示返回的字符個數

let a = "hello world"
let b = a.substr(2, 3)
//"llo"
let b = a.substr(2, 5)
//"llo w"

substring方法
substring方法:第一個參數指定子字符串開始位置,第二個參數表示子字符串最後一個字符後面的位置

let a = "hello world"
let b = a.substring(2, 3)
//"l"
let a = "hello world"
let b = a.substring(2, 7)
//"llo w"

split方法
split方法是基於指定的字符,將字符串分割成字符串數組 當指定的字符爲空字符串時,將會分隔整個字符串

let a = "hello world 123 qwe qwqe"
a.split(" ")
//["hello", "world", "123", "qwe", "qwqe"]

replace方法
字符串替換

let a = "hello world"
a.replace("e", "www")
//"hwwwllo world"

indexOf
獲取子字符串在在字符串中的位置

let a = "hello world"
a.indexOf("ell")
//1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章