Having problem to understand [Search and Replace]

Here is the problem known as Search and Replace.
It’s saying,

Preserve the case of the first character in the original word when you are replacing it. For example if you mean to replace the word “Book” with the word “dog”, it should be replaced as “Dog”.

But in test case there is,

myReplace("Let us go to the store", "store", "mall") should return “Let us go to the mall”.

and also,

myReplace("His name is Tom", "Tom", "john") should return “His name is John”.

I wrote code to change all after values from myReplace function to capitalize.

Why mall should not return Mall but, john should return John?

In the resulting sentence, the capitalization of after word should be the same as has before word.

I don’t understand :roll_eyes:
It’s said,

Note:
Preserve the case of the first character in the original word when you are replacing it. For example if you mean to replace the word “Book” with the word “dog”, it should be replaced as “Dog”.

Hi @Plabon_Kumer_Sarker

From your code, I don’t think you are doing what is expected to get the desired output.

  1. Look at the loop below which is in your code
for(let i=0; i<str.length; i++){
    if(before === strArr[i]){
      point = i;
    }
  }

You are looping through the characters in the string and examine what you are checking in the the if condition. Don’t you see a problem there?
2. And var next = (after[0].toUpperCase()).concat(after.slice(1));. What are you doing there? Don’t you see a problem there too. I suggest you read the task again.

1 Like

@nibble I understand the error 1.

Here I looped through str instead of strArr. But I don’t understand error 2 that you said,

Here my intention is to capitalize after as this problem said in Note :.

Capture

The instruction didn’t ask you to capitalize all the time. What it wants you to do is for example if before is Dog and after is cat, then change cat to Cat however if before is dog and after is cat, then you don’t change anything. Similarly if before is dog and after is Cat, then change Cat to cat. Instead of what you did, I would have gone with something like:

const firstChar  = before.charAt(0);
let next;
if(firstChar.toUpperCase() === firstChar ){
  next = after[0].toUpperCase() + after.slice(1);
}else{
  next = after[0].toLowerCase() + after.slice(1);
  }
2 Likes

@nibble Thank you so much :gift_heart:
It was tricky for me. :frowning:

1 Like

I am glad to be of help. Happy hacking.

1 Like

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