String Method
Method Table
Match(regex)
Replace(egexp|substr, newSubstr|function)
原來 replace 也是可以帶 function 的喔
function 參數解釋
Last updated
原來 replace 也是可以帶 function 的喔
function 參數解釋
Last updated
Method
return
example
trim()
沒有多餘空格的 “字串” (只會移掉兩端空白)
" s".trim(); // "s"
Capture some words
indexOf(searchValue[, fromIndex])
搜尋字串(searchValue) 所在的 “位置 (Number)” 第二個參數 fromIndex 可以指定從哪個位置開始搜尋,若找不到會回傳 -1
'Blue'.indexOf('blue'); // -1
charAt(index)
位置(index) 所在的 “字串”,若找不到會回傳 ” 空字串
'Brave new world'.charAt(4) // e
substr(start[, length])
從 start 這個位置開始,總長 length 的 “字串”.若 length 沒有值則等於等於從 start 到字串最後一個字都抓出來
'abcdefghij'.substr(1, 2) // bc
Find something
match(regex)
符合 regex 條件的 “Array”,若沒有丟參數進去 Array[0] 會是 “” 空字串,若參數 regex 都不符合會回傳 null
"hannah1".match(/\d/i);
// [1, index: 6, input: 'hannah1'...]
search(regex)
符合 regex 條件並第一個找到的 Number,若找不到就會回傳 -1
"hey JudE".search(/[A-Z]/g) // 4
replace(regexp|substr, newSubstr|function)
原本字串用 regex 或 substr 搜尋,找到符合條件就用 newSubstr 取代成為新字串
var str = 'Twas the night before Xmas...';
str.replace(/xmas/i, 'Christmas');
slice(beginIndex[, endIndex])
切過的新字串(包含 beginIndex 不含 endIndex)
split([separator[, limit]])
(拆開) 回傳經過 separator 拆開的 Array,可以搭配使用 Array.join() 組合成不一樣的字串 (也可以用 regex)
"hi hana".split(" ");
// ['hi', 'hana']
split(/[^a-z]/)
// split 不是 alpha 的
includes(searchString[, position])
Boolean
'To be, or'.includes('To be') // true
charCodeAt(index)
將英文字母轉為 ASCII Code
'Aao'.charCodeAt(1) // a 是 97
String.fromCharCode(Number[, Number])
將數值轉換成回字串
String.fromCharCode(65, 97, 111) // Aao
Possible name
Supplied value
match
The matched substring. (Corresponds to $&
above.)
p1, p2, ...
The nth string found by a parenthesized capture group, provided the first argument to replace()
was a RegExp
object. (Corresponds to $1
, $2
, etc. above.) For example, if /(\a+)(\b+)/
, was given, p1
is the match for \a+
, and p2
for \b+
.
offset
The offset of the matched substring within the whole string being examined. (For example, if the whole string was 'abcd'
, and the matched substring was 'bc'
, then this argument will be 1.)
string
The whole string being examined.