Skip to content

Instantly share code, notes, and snippets.

@jnsprnw
Last active May 2, 2016 12:26
Show Gist options
  • Save jnsprnw/e42fd94f2ef25b988df931942ffe76c2 to your computer and use it in GitHub Desktop.
Save jnsprnw/e42fd94f2ef25b988df931942ffe76c2 to your computer and use it in GitHub Desktop.
Build a conditional String in JavaScript
var foo = 'Hello'
var bar = 'World'
function clean (str) {
return str.trim().replace(/\s\s+/g, ' ');
}
// With ES6
function buildES6 (foo, bar) {
return clean(`${foo || ''} ${bar || ''}`);
}
// Without ES6
function buildWithoutES6 (foo, bar) {
return clean((foo || '') + ' ' + (bar || ''));
}
// With array
function buildArray (foo, bar) {
var arr = [];
arr.push( foo || '', bar || '' );
return arr.join(' ');
}
// With string concatenation operator
function buildConcat (foo, bar) {
return clean(""
+ ( foo || '' )
+ ' '
+ ( bar || '' ));
}
console.log(buildES6(foo, bar));
// "Hello World"
console.log(buildWithoutES6(foo, bar));
// "Hello World"
console.log(buildArray(foo, bar));
// "Hello World"
console.log(buildConcat(foo, bar));
// "Hello World"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment