Can my code be cleaned up at all?

Tell us what’s happening:
My solution to replacing the ‘before’ with the ‘after’ in a ‘str’ is below. I wanted to know if it could be shortened any to fewer lines, like if i can do more than 1 of the array methods on 1 line or not. I had to makeup 3 dummy variables just to save each step to be used in the next step…but it doesnt seem right to need to do that. I was hoping I could do like: d.shift().unshift( c) and/or after[0].toUpperCase().split("") to combine steps but i get errors…?

I’m having a hard time with array methods in terms of when I need to assign them to a new variable vs when they automatically update the existing array i.e. (arr.pop(“hi”) --automatically updates the arr with the entry “hi”…vs let a = arr.join("") --requires a new variable assignment to work). I was told before u just need to memorize which array method needs a variable assigned to work and which doesn’t, but as I said it looks ridiculous having to makeup all these dummy variables to relay 1 line’s ouput into the next line’s input.

I checked the other answers, i’d like to just get ‘this way’ cleaned up as much as possible.

Your code so far


function myReplace(str, before, after) {
let after2 = after 
//if before is capitalized, capitalize after by making into array
if (before[0].match(/[A-Z]/)) {
let c = after[0].toUpperCase()
let d = after.split("")
d.shift()
d.unshift(c)
after2 = d.join("")
}
//replace before with after in the str
return str.replace(before,after2)

}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36.

Challenge: Search and Replace

Link to the challenge:

you can chain functions:

function1().function2().function3();

This is something I see often with answers that kicked my ass!

but careful about chaining functions, you can do that only some times, it depends on what the method returns

  • you could use test() instead of match()
  • you could replace many of the lines in your code with the replace() method, or with string chaining and slice (you don’t need to make after an array to change the first letter)
1 Like

can u elaborate on what u mean by using replace()?

like string = string.replace( /* uppercase letter */ , /* lowercase letter */ )

you use replace to replace the letter

1 Like

oh ok. i originally tried that actually. but the problem was how to put a variable inside a
/ /. I googled it and was left too confused so i didnt go that route,

replace doesn’t actually need a regex there, you can just put a string. if you use a regular expression can do more, but as you just want to change a letter, you can do it with just a variable

The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. If pattern is a string, only the first occurrence will be replaced.

from here:

ok. If we were just looking at the if statement above tho (changing the capital of the first letter) and the array methods I am using, there’s no other way to arrange/simplify them into shorter code with the route I chose?
Other than using a ternary expression.

I was talking about that part, there is no need to make an array for what you are doing, that would simplify a lot

if you do not like replace, you can use string concatenation

after2 = /* first letter made upper case */ + /* rest of the string */

The point is to simplify while keeping the ‘route’ i chose tho. So I chose to turn it into an array and do xyz etc. Can I re-arrange xyz in fewer lines was what I meant, just the fact my logic is there but I have to write it on soooo many different lines was the issue. Like ternary would save some characters for example. So is there some kind of rearrangement where similar methods are used and it’s just 1 giant return or…i don’t know, point was to keep the method of solving intact…so array to change the char…etc. I alrdy looked over the solutions page for the other ways of solving.

change the first character of the array, instead of using shift/unshift, that will reduce it to three lines

// string to array
// change first character
// array to string

Why do you want to shorten the code, though? Is there some criteria that says “short code is better”?

Please remember to write clear code. Code that clearly states your intent, is easy to read and understand.

As for shortening your specific code, I don’t really understand what you’re trying to do. From the looks of it, it should be better to do one of the following:

  • use replace
  • split string into array of words, find the replacement candidate, replace array element, join words back into string

You can use string.split(' ') to split on spaces and array.join(' ') to insert those spaces back. This way you’ll have each word separated and can compare each word with “before” to replace it with “after” using a for loop.

This would also allow you to shorten your code quite a bit and you won’t have to worry about shift and unshift. Here’s some example one-liner.

function myReplace(source, target, replacement) {
  return source.split(' ').map(word => word === target ? replacement : word).join(' ');
}

Please note: I rarely use one-liners in production unless they’re very clean. Typically I’d split this into several lines of code and assign variables to each - it is much, MUCH easier to debug code that is split into separate statements compared to one-liners.

A longer version of the above code would be the following:

function myReplace(source, target, replacement) {
  let array = source.split(' ');
  for (let i = 0; i < array.length; i++) {
    if (array[i] === target) {
      array[i] = replacement;
    }
  }
  return array.join(' ');
}

Hope it helps!
Have a nice day!

I should probably make this my signature instead of typing it in every message :smiley:

-add-
Just to address something that had me concerned:

I’ve never seen array pop doing anything other than removing the last element of the array, which is the entire behavior according to MDN:

It should remove an element at the end of the array and return it to the caller. If you assign the result of “pop” to a variable, you can use the element you’ve popped. Or you can use it right away if you don’t want to save it to a variable.

As for “you just have to memorize” - I’m afraid so. You’ll have to memorize what methods do what, and there’ll be a lot of memorization. Luckily for us, we don’t need to memorize as much as medics do. Unluckily, we do have to memorize a ton of stuff.