[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/substring [Back]  [Original]

String.prototype.substring() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

String.prototype.substring()

20157

String substring()

const str = "Mozilla";

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

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

js
substring(indexStart)
substring(indexStart, indexEnd)

indexStart

indexEnd

substring() indexStart indexEnd

  • indexEnd substring()
  • indexStart indexEnd substring()
  • indexStart indexEnd substring()

0 str.length 0 str.length

NaN 0

substring()

substring "Mozilla"

js
const anyString = "Mozilla";

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

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

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

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

substring() length

substring() length

js
const text = "Mozilla";

//  4 
console.log(text.substring(text.length - 4)); // illa

//  5 
console.log(text.substring(text.length - 5)); // zilla

substring() substr()

substring() substr()

  • substr() start length substring() start end
  • substr() start substring() 0
  • substr() substring() end start

substr() ECMAScript

js
const text = "Mozilla";
console.log(text.substring(2, 5)); // "zil"
console.log(text.substr(2, 3)); // "zil"

substring() slice()

substring() slice()

substring() indexStart indexEnd slice()

js
const text = "Mozilla";
console.log(text.substring(5, 2)); // "zil"
console.log(text.slice(5, 2)); // ""

NaNsubstring() 0

js
console.log(text.substring(-5, 2)); // "Mo"
console.log(text.substring(-5, -2)); // ""

slice() NaN 0

js
console.log(text.slice(-5, 2)); // ""
console.log(text.slice(-5, -2)); // "zil"

slice()

Brave New World Brave New Web

js
//  fullS  oldS  newS
function replaceString(oldS, newS, fullS) {
  for (let 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");

oldS newS "OtherWorld" "World"

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

String.prototype.replace()

ECMAScript 2027 LanguageSpecification
# sec-string.prototype.substring


Web Proxy Viewer  |  New URL  |  Original Page