Using slice on a string consisting of numbers


I’m completing a challenge where I need to concatenate two strings at the point where the letter passed in is in both letters, so ‘hello’, ‘world’ and ‘l’ should return ‘held’.

My code works for strings of letters, but for some reason not a string of numbers. Could someone tell me what’s going on here?


function stringMerge(string1, string2, letter) {

  let one = string1.indexOf(letter);

  let firstPart = string1.slice(string1[0], one+1)
  let two = string2.indexOf(letter)
  let secondPart = string2.slice(two + 1, string2.length)
  return firstPart + secondPart

stringMerge("12345654321","123456789", "6")

I don’t think you need string1[0] in firstPart, just 0.


Do you happen to have any idea why it worked on other strings?

If the begin index is undefined, slice begins from index 0. I think that if you pass a string as and index, it will be treated as undefined.

1 Like