1

I have the following code:

function myJoin(array, separator) {

  let newStr = array.join(separator).replace("\", "")

    return newStr

  }

  myJoin(['let\'s', 'make', 'a', 'list'], ' ');

I expect the output to be: "let's make a list" but instead it gives me an error.

evalmachine.<anonymous>:21
  let newStr = array.join(separator).replace("\", "")
                                                   ^^
SyntaxError: Invalid or unexpected token

What's wrong with my replace method?

1
  • 1
    array.join(separator).replace("\\", "") Commented Mar 24, 2019 at 16:08

4 Answers 4

1

The problem is with "\". The backslash escapes the end quote, meaning the string is unclosed. It should be "\\" instead.

Here's a code example:

function myJoin(array, separator) {
  const newStr = array.join(separator).replace('\\', '')
  return newStr
}

const result = myJoin(['let\'s', 'make', 'a', 'list'], ' ')
console.log(result)

If you're interested, here's an article on escape characters.

Sign up to request clarification or add additional context in comments.

1 Comment

@PineNuts0 No, it doesn't. I just added a console.log, you can run it to check.
1

You don't need replace()

The \ in your string isn't really a character — it's part of an escape sequence. As a result, you don't need to replace it unless you are trying to replace actual, literal backslashes in the string. This does what you would expect:

function myJoin(array, separator) {
    return array.join(separator) // you don't need replace here
}
  
console.log(myJoin(['let\'s', 'make', 'a', 'list'], ' '))
  

Comments

0

The problem is "\". Backslash is a quoting character in JavaScript which causes the next character to be treated literally. You need to write "\\" to create a string of one backslash character.

Comments

0

You are escaping the " inside of your replace, you have to use 2 backslashes, ie: \\. Also, replace() is not a function for arrays, this must be done on a string, so you must also swap put join() before replace().

This will do the trick:

console.log(['let\'s', 'make', 'a', 'list'].join(" ").replace("\\", ""));

It looks like you would like this to be applied to array's specifically, how about prototypes?

Array.prototype.replace = function(separator = " ") {
  return this.join(separator).replace("\\", "");
};

// Can be called like so 
console.log(['let\'s', 'make', 'a', 'list'].replace(" "));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.