JavaScript
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:
- source
- pattern
- 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
replaceorreplaceAllis forbidden.
Tips:
- Use a combination of
indexOf,substringandconcat.
Tests
- 1
You should define a function named
myReplace. - 2
myReplace("The past is what I say it is.", "I", "they")should return"The past is what they say it is.". - 3
myReplace("Fire", "Fire", "Earth")should return"Earth". - 4
myReplace("Water Fire Fire", "Fire", "Earth")should return"Water Earth Fire".