PineNuts0
PineNuts0

Reputation: 5234

JavaScript: Use Join to Make Array a String Using Input Argument as Separator Btw Words --> Replace Error

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?

Upvotes: 1

Views: 104

Answers (4)

Mark
Mark

Reputation: 92440

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'], ' '))
  

Upvotes: 1

Miroslav Glamuzina
Miroslav Glamuzina

Reputation: 4557

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(" "));

Upvotes: 0

kognise
kognise

Reputation: 632

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.

Upvotes: 1

David Goldfarb
David Goldfarb

Reputation: 1886

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.

Upvotes: 0

Related Questions