andrewplummer / Sugar

A Javascript library for working with native objects.
https://sugarjs.com/
MIT License
4.53k stars 306 forks source link

String.Format returning "undefined" #593

Closed cacothi closed 6 years ago

cacothi commented 7 years ago

Exemple:

"This {first} is nice for {second}!!!".format({first: "test"});

Results: This test is nice for undefined!!!

Expect result: This test is nice for !!!

The problem: If the {second} is not provided, it gets replaced by the literal undefined

or maybe an option to set a fallback for unknown parameters.

andrewplummer commented 7 years ago

This is something you have to handle yourself. It's common in Javascript to get "undefined" as a string unexpectedly since that is in fact it's string value. You can see this yourself with String(undefined). Sugar is intended to be a utility library that is an extension of Javascript itself, so in that sense I don't believe that it provides value to mask or convolute the natural way that JS works, even if it can be quite quirky.

cacothi commented 7 years ago

@andrewplummer , I do understand it, what I mean is that, using the power of Sugar, would be nice to don't show UNDEFINED on the return. Normaly, we developers, use it to display a message and it's not nice to the final user reads UNDEFINED even not being able to get the value.

Giving you a real example, let's suppose that you are using Sugar on NodeJS to send an SMS message, and you have the following template: "Hi {name}, this is your code..."

It would be much more friendly with a return like: "Hi , this is your code..."

Than "Hi undefinded, this is your code..."

In case: var user = null; "Hi {name}, this is your code...".format(user);

It's just a real world situation of format usage, but no worries, I'll find n replace "undefined" for empty. It was just a suggestion as I believe that javascript has no limit to solve this issue.

andrewplummer commented 7 years ago

So, in that case you simply use: value || '' ... this is the standard way to handle what you're talking about, so it should be expected.

andrewplummer commented 7 years ago

Also check out Object.defaults ... this can help you here too.