Search and Replace help!

Search and Replace help!
0

#1

Could anyone please instruct me as to why this code doesn’t seem to change the first letter of the replacement word to the correct format.
Everything else seems to be working.


#2

Would you mind pasting your full code into a reply, so we can debug it for you faster?

To enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#3

Never mind, I figured out why your code does not work. The first if statement (see below) evaluates to true, so you replace “Tom” with “john” in the str and reassign to str, so now str = “His name is john”

  if (before.charAt(0)===before.charAt(0).toUpperCase() || before.charAt(0)===before.charAt(0).toLowerCase()) {

The second if statement (see below) evaluates to false, so the else block of code first assigns the capital letter “J” to affter and then you attempt to replace “Tom” with the capital letter “J”. There is no “Tom” in str at this point, so str is still equal to “His name is john”.

if (before.charAt(0)!==before.charAt(0).toUpperCase()) {

Finally your function returns “His name is john”


#4

did it like this in the end quite different but more easy to understand


#5

Glad you got it figured out.

BTW - A shorter version of your if that does not involve using charAt(0) would be to just reference the first index of each string.

if (before[0].match(capital_letter) && after[0].match(small_letter)) {