Skip to content

Instantly share code, notes, and snippets.

@colynb
Created August 19, 2012 01:27
Show Gist options
  • Save colynb/3390791 to your computer and use it in GitHub Desktop.
Save colynb/3390791 to your computer and use it in GitHub Desktop.
JS: Wrap Terms With...
/*
* Take a string and wrap any terms with some container (like <span>)
* Nothing complicated. It splits a string on ',' (comma) and 'and', and adds the desired wrapper around the resulting terms.
*/
​var str = 'Web Developer and Front-End Engineer and All around cool guy';
String.prototype.wrapTermsWith = function(wrap) {
var delimiters = [',', ' and '],
wrapper = wrap.split('><'),
start = wrapper[0] + '>',
end = '<' + wrapper[1],
newStr = start + this;
for (var i = 0; i < delimiters.length; i++) {
newStr = newStr.split(delimiters[i]).join(end + delimiters[i] + start);
}
return newStr + end;
}
var newString = str.wrapTermsWith('<span></span>');
$('#job-title').html(newString);​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment