JS:String.prototype.substring()方法

JS:String.prototype.substring()方法

String.prototype.substring()方法返回字符串開始和結(jié)束索引之間的部分吱七,或者返回字符串開始索引至字符串的結(jié)尾缝龄。

JavaScript Demo: String.substring()

var str = 'Mozilla';

console.log(str.substring(1, 3));
// expected output: "oz"

console.log(str.substring(2));
// expected output: "zilla"

Syntax/語(yǔ)法

String.prototype.substring(indexStart[, indexEnd]);

  • Parameters/參數(shù):

    • indexStart
      • The index of the first character to include in the returned substring.
      • 要返回的子字符串中的第一個(gè)字符的索引。
    • indexEnd
      • Optional. The index of the first character to exclude from the returned substring.
      • 可選的所宰。要返回的子字符串中排除的第一個(gè)字符的索引。
  • Return Value
    • A new string containing the specified part of the given string.

Description

  • substring() extracts characters from indexStart up to but not including indexEnd. In particular:

    • If indexEnd is omitted, substring() extracts characters to the end of the string.
      (如果indexEnd是被省略的,substring()將提取字符直到字符串的結(jié)束疯搅。)
    • If indexStart is equal to indexEnd, substring() returns an empty string.
      (如果indexStart等于indexEnd表制,substring()將返回一個(gè)空的字符串健爬。)
    • If indexStart is greater than indexEnd, then the effect of substring() is as if the two arguments were swapped; See example below.(如果indexStart大于indexEnd,效果相當(dāng)于兩個(gè)參數(shù)調(diào)換;示例在下面么介。)
  • Note: Any argument value that is less than 0 or greater than stringName.length is treated as if it were 0 and stringName.length respectively. Any argument value that is NaN is treated as if it were 0.
    任何小于0或大于stringName.length的參數(shù)值將被視為0或stringName.length娜遵。任何NaN的參數(shù)值都將被視為0。

示例

Using substring()

The following example uses substring() to display characters from the string 'Mozilla':

下面的示例使用substring()從字符串'Mozilla'中提取字符:

var anyString = 'Mozilla';

// Displays 'M'
console.log(anyString.substring(0, 1));
console.log(anyString.substring(1, 0));

// Displays 'Mozill'
console.log(anyString.substring(0, 6));

// Displays 'lla'
console.log(anyString.substring(4));
console.log(anyString.substring(4, 7));
console.log(anyString.substring(7, 4));

// Displays 'Mozilla'
console.log(anyString.substring(0, 7));
console.log(anyString.substring(0, 10));

Using substring() with length property

The following example uses the substring() method and length property to extract the last characters of a particular string. This method may be easier to remember, given that you don't need to know the starting and ending indices as you would in the above examples.

// Displays 'illa' the last 4 characters
var anyString = 'Mozilla';
var anyString4 = anyString.substring(anyString.length - 4);
console.log(anyString4);

// Displays 'zilla' the last 5 characters
var anyString = 'Mozilla';
var anyString5 = anyString.substring(anyString.length - 5);
console.log(anyString5);

Difference between substring() and substr()

There's a subtle difference between the substring() and [substr()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr) methods, and you should be careful not get them confused.

The arguments of substring() represent the starting and ending indexes, while the arguments of substr() represent the starting index and the length of characters to include in the returned string.

var text = 'Mozilla';
console.log(text.substring(2,5)); // => "zil"
console.log(text.substr(2,3)); // => "zil"

Replacing a substring within a string

The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string 'Brave New World' to 'Brave New Web'.

// Replaces oldS with newS in the string fullS
function replaceString(oldS, newS, fullS) {
  for (var i = 0; i < fullS.length; ++i) {
    if (fullS.substring(i, i + oldS.length) == oldS) {
      fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length);
    }
  }
  return fullS;
}

replaceString('World', 'Web', 'Brave New World');

Note that this can result in an infinite loop if oldS is itself a substring of newS — for example, if you attempted to replace 'World' with 'OtherWorld' here. A better method for replacing strings is as follows:

function replaceString(oldS, newS, fullS) {
  return fullS.split(oldS).join(newS);
}

The code above serves as an example for substring operations. If you need to replace substrings, most of the time you will want to use String.prototype.replace().

Link to MDN section

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末壤短,一起剝皮案震驚了整個(gè)濱河市设拟,隨后出現(xiàn)的幾起案子慨仿,更是在濱河造成了極大的恐慌,老刑警劉巖纳胧,帶你破解...
    沈念sama閱讀 212,080評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件镰吆,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡跑慕,警方通過查閱死者的電腦和手機(jī)万皿,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,422評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)核行,“玉大人牢硅,你說我怎么就攤上這事≈パ” “怎么了减余?”我有些...
    開封第一講書人閱讀 157,630評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)惩系。 經(jīng)常有香客問我佳励,道長(zhǎng),這世上最難降的妖魔是什么蛆挫? 我笑而不...
    開封第一講書人閱讀 56,554評(píng)論 1 284
  • 正文 為了忘掉前任赃承,我火速辦了婚禮,結(jié)果婚禮上悴侵,老公的妹妹穿的比我還像新娘瞧剖。我一直安慰自己,他們只是感情好可免,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,662評(píng)論 6 386
  • 文/花漫 我一把揭開白布抓于。 她就那樣靜靜地躺著,像睡著了一般浇借。 火紅的嫁衣襯著肌膚如雪捉撮。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,856評(píng)論 1 290
  • 那天妇垢,我揣著相機(jī)與錄音巾遭,去河邊找鬼。 笑死闯估,一個(gè)胖子當(dāng)著我的面吹牛灼舍,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播涨薪,決...
    沈念sama閱讀 39,014評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼骑素,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了刚夺?” 一聲冷哼從身側(cè)響起献丑,我...
    開封第一講書人閱讀 37,752評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤末捣,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后创橄,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體塔粒,經(jīng)...
    沈念sama閱讀 44,212評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,541評(píng)論 2 327
  • 正文 我和宋清朗相戀三年筐摘,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了卒茬。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,687評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡咖熟,死狀恐怖圃酵,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情馍管,我是刑警寧澤郭赐,帶...
    沈念sama閱讀 34,347評(píng)論 4 331
  • 正文 年R本政府宣布,位于F島的核電站确沸,受9級(jí)特大地震影響捌锭,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜罗捎,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,973評(píng)論 3 315
  • 文/蒙蒙 一观谦、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧桨菜,春花似錦豁状、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,777評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至霞掺,卻和暖如春谊路,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背菩彬。 一陣腳步聲響...
    開封第一講書人閱讀 32,006評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工缠劝, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人挤巡。 一個(gè)月前我還...
    沈念sama閱讀 46,406評(píng)論 2 360
  • 正文 我出身青樓剩彬,卻偏偏與公主長(zhǎng)得像酷麦,于是被迫代替她去往敵國(guó)和親矿卑。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,576評(píng)論 2 349

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,312評(píng)論 0 10
  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,448評(píng)論 0 13
  • Lua 5.1 參考手冊(cè) by Roberto Ierusalimschy, Luiz Henrique de F...
    蘇黎九歌閱讀 13,766評(píng)論 0 38
  • “之前我還在聽你講故事轻黑,現(xiàn)在我卻成了故事中 的人,時(shí)間好快”這是鄰居家小弟昨晚跟我說的一句話琴昆,他今年在部隊(duì)待的第八...
    至此一生_閱讀 519評(píng)論 0 1
  • 我算是一個(gè)內(nèi)向的人氓鄙,內(nèi)向的人做得最多的事情就是跟自己交談,而跟自己交談最好的辦法就是寫作业舍,這是一種非常清晰的抖拦,能夠...
    xiaohuialex閱讀 694評(píng)論 0 3