3種實(shí)現(xiàn)在JavaScript中提取子字符串的方法

英文 | https://medium.com/programming-essentials/how-to-extract-a-substring-in-javascript-e0d521cb030f
翻譯 | 小愛(ài)
有3種方法可以提取JavaScript中字符串的一部分,也許你覺(jué)得這個(gè)方法太多了。你只需要一個(gè)就足夠了。
下面我們就開(kāi)始吧。
01、substr
該substr(start, length)方法提取字符串的一部分,從指定的索引處開(kāi)始,并返回指定數(shù)量的字符。
const quote = "Winter is coming";const part1 = quote.substr(0, 6);//Winterconst part2 = quote.substr(10, 6);//coming
請(qǐng)注意,第一個(gè)字符在index處為0。
該start指數(shù)是必需的,但 length是可選的。如果省略,它將提取字符串的其余部分。
const quote = "Winter is coming";const part = quote.substr(6);// is coming
02、substring
該substring(start, end)方法返回start和end索引之間的字符串部分。它從start索引處的字符開(kāi)始到結(jié)束,但不包括索引處的字符end。
const quote = "We Stand Together";const part = quote.substring(3, 8);// Stand
如果end省略索引,它將提取到字符串的末尾。
const quote = "We Stand Together";const part = quote.substring(3);// Stand Together
與indexOf方法結(jié)合使用,效果會(huì)更好。
該indexOf方法返回第一個(gè)索引,在該索引處可以找到給定的字符串文本,否則返回-1。
考慮以下代碼在第一個(gè)逗號(hào)之后提取文本。
const quote = "You know nothing, Jon Snow";const commaIndex = quote.indexOf(",");const part = quote.substring(commaIndex + 1);//" Jon Snow"
03、slice
該slice(start, end)方法返回start和end索引之間的字符串部分。slice像substring。
const quote = "We Stand Together";const part = quote.slice(3, 8);// Stand
如果end省略索引,它將提取到字符串的末尾。
const quote = "We Stand Together";const part = quote.slice(3);// Stand Together
slice基本上是為了模仿陣列接口而添加的。(數(shù)組中有一個(gè)同名的方法在兩個(gè)索引之間提取其一部分,并返回一個(gè)新的淺表副本)。
字符串在JavaScript中是不可變的。所有這些方法都不會(huì)更改原始字符串。
最后,謝謝你的閱讀。
