Search and Replace

function myReplace(str, before, after) {

// Step 1: Turn the str into an array
// Step 2: Find the index 'before' is located
// Step 3: Check if the before is uppercase or lowercase
// Step 4: Replace before with after (with correct case)

  return str;

console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));

Are my steps correct for this problem? I think I understand what needs to be done when I put it in simple terms, I’m struggling to translate that into code though

How are you going to do step 2? Remember, you aren’t just looking for one character. You are replacing a word, which will most likely be more than one character.

Did you learn about the replace method for strings in a previous lesson? That seems like it might be a good fit.

In order to do step 2 I have to write code that finds where before is in the str. Would the best way to do this be breaking the str up so each word is it’s own array?

I was really confused by the Pig Latin question and after being stuck for hours I decided to move on to this question, but the replace method was introduced before and I did understand it, but I have trouble retaining the information and applying it myself without examples being given in the question like they do for some. I will brush up on the replace method and try to use it for this

You could definitely solve this by breaking the sentence up into words and putting them in an array. The twist here is that you need to take into account that the first letter of the word you want to replace could be either lower or upper case. I think using the replace method might allow you to write more concise code but it adds the slight complexity of having to use a regular expression.

Ahhhh so something like this?

function myReplace(str, before, after) {

  const reg = /A-Za-z/;
  const newStr = str.replace(reg, (before,after); 
  return newStr;

console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));
function myReplace(str, before, after) {

  if (/^[A-Z]/.test(before)) {
 after = after[0].toUpperCase() + after.substring(1)
  } else {
    after = after[0].toLowerCase() + after.substring(1)

  return str.replace(before,after); 

myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

Can someone help me understand what + after.substring(1) is doing?

Hiii, can someone please help me understand a small part of this solution if they have the time? Thanks:)

Why did you add it? What did you intend the syntax to do?

Ahhh to add all the letters following the first letter?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.