Skip to content

Instantly share code, notes, and snippets.

@yckart
Last active October 26, 2016 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yckart/32a415acdc79e4815c52 to your computer and use it in GitHub Desktop.
Save yckart/32a415acdc79e4815c52 to your computer and use it in GitHub Desktop.
Interesting concept to wrap strings around each array-item.

This is something I fiddled with during development. A really helpful thing if we need to wrap strings around array items.

var values = [1, 3, 3, 7];
var open = '<span>';
var close = '</span>';
var html = open + values.join(close + open) + close;

console.log(html); // => "<span>1</span><span>3</span><span>3</span><span>7</span>"

This could be a simple one-liner:

'<span>' + [1, 3, 3, 7].join('</span>' + '<span>') + '</span>';

...or wrapped as a great helper-function, see below

I stumbled over this by creating html tables as strings:

//     |----------------------------------------------------------- TABLE --------------------------------------------------|
//                                  |----------------------------- ROW ------------------------------|
//                                            |----------------- CELL --------------------|
return '<table>' + data.map(row => '<tr>' + ('<td>' + row.join('</td>' + '<td>') + '</td>') + '</tr>').join('') + '</table>'

Other concepts

var options = ''
for (var i = 0; i < ranges.length; i++) options += '<option value="'+ranges[i]+'"></option>'

var options = '<option value="' + ranges.join('"></option><option value="') + '"></option>'

var options = ranges.map((range) => '<option value="'+range+'"></option>').join('')
/**
* Wraps opening and closing strings around each array-item.
*
* @param Array values Some values you want to wrap, e.g. `"Foo isn't equal to bar.".split('')`
* @param String open Opens a new html-tag, e.g. `"<span>"`
* @param String close Closes the openend html-tag, e.g. `"</span>"`
*/
var wrapArrayItems = function (values, open, close) {
return open + values.join(close + open) + close;
};
<?php
/**
* Wraps opening and closing strings around each array-item.
*
* @param Array values Some values you want to wrap, e.g. `"Foo isn't equal to bar.".split('')`
* @param String open Opens a new html-tag, e.g. `"<span>"`
* @param String close Closes the openend html-tag, e.g. `"</span>"`
*/
function wrapArrayItems($values, $open = '<span>', $close = '</span>') {
return $open . implode($close . $open, $values) . $close;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment