Skip to content

Conversation

@FadyMak
Copy link

@FadyMak FadyMak commented Nov 12, 2016

Issue #230

} catch (e) {}

name = name && name.toString().trim()
name = name && JSON.stringify(name.toString().trim()).slice(1, -1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How come .slice is needed here?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The extra quotes:

> var x = JSON.stringify('hello "me" you').slice(1, -1) > x 'hello \\"me\\" you' > var x = JSON.stringify('hello "me" you') > x '"hello \\"me\\" you"'
Copy link

@sayanriju sayanriju Nov 13, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The extra quotes slashes seems to be a quirk on the node REPL. It should work fine if you are running it in a script.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sayanriju JSON.stringify('hello') will result in an additional set of quotes around the output:

console.log(JSON.stringify('hey')) // "hey"

i.e.: the resultant string is actually "hey" as opposed to just hey

In our case, we don't want the resultant Git user.name to be wrapped in quotes but we would like to escape them:

var gitConfigName = 'hello "me" you' var packageJSON = { author: JSON.stringify('hello "me" you').slice(1, -1) } console.log(packageJSON) // { author: 'hello \\"me\\" you' } packageJSON = { author: JSON.stringify('hello "me" you') } console.log(packageJSON) // { author: '"hello \\"me\\" you"' }

I hope that helps clear it up a bit.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My bad! I mean slash, not quote (The extra ones in "me"). :P
Anyway, it did clear things up.

BTW, I guess JSON.stringify is preferred over String.replace due to the slight performance hit?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think performance is that much of a concern here since we only call it once and it's for the CLI which isn't performance-critical.

I chose to use JSON.stringify instead of String.replace in hopes that it will cover some cases like escaping single quotes:

JSON.stringify("'hey' there")

(not sure if it would appear in the user.name but it's not a bad idea to protect against it)

@zigomir
Copy link
Contributor

zigomir commented Nov 13, 2016

Thanks @FadyMak!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants