JavaScript String Type

Substring

We can extract a piece of a string using the substring method. This method takes a mandatory starting index and an optional ending index. If the end index is not specified, it defaults to the end of the string.

const quote = `No-one chooses me.
I do not give anyone that right.
I am Karsa Orlong of the Teblor.
All choices belong to me.
`
const name = quote.substring(57, 69)
console.log(name) // "Karsa Orlong"

Read more on MDN

String.prototype.replace()

Test yourself

Description

Define a new function with the name

myReplace

that takes three string input parameters:

  1. source
  2. pattern
  3. replacement

and replaces the first occurrence of the pattern with the replacement of the source string.

In other words we're implementing a simplified version of the replace method.

Assumptions:

  • Pattern will match at least once.

Restrictions:

  • Use of replace or replaceAll is forbidden.

Tips:

  • Use a combination of indexOf, substring and concat.

Tests

  1. 1 You should define a function named myReplace.
  2. 2myReplace("The past is what I say it is.", "I", "they") should return "The past is what they say it is.".
  3. 3myReplace("Fire", "Fire", "Earth") should return "Earth".
  4. 4myReplace("Water Fire Fire", "Fire", "Earth") should return "Water Earth Fire".
Editor