Reputation: 901
I define an absorbing String simply as follows: When concatenated with any other String, the result is empty String (another absorbing element).
I know that probably such element doesn't exist natively in JavaScript, but I came up with a simple logic that simulate this
"_".repeat(str.length/str.length)+ str+ "_".repeat(str.length/str.length)
Example:
var str = "HP";
var result = "_".repeat(str.length/str.length)+ str+ "_".repeat(str.length/str.length);
[out]: "_HP_"
str = "";
var result = "_".repeat(str.length/str.length)+ str+ "_".repeat(str.length/str.length);
[out]: ""
The purpose is simply to have underscores besides String only when they exist.
This is very helpful when many String are concatenated with one separator, and that we would like to avoid If Else block-like code.
Is there a shorter form?
Upvotes: 0
Views: 111
Reputation: 386578
You could use a logical AND &&
wich checks the string for truthyness.
function pad(string) {
return string && '_' + string + '_';
}
console.log(pad("HP"));
console.log(pad(""));
Upvotes: 2