Skip to content

Instantly share code, notes, and snippets.

@thegitfather
Last active July 13, 2021 15:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thegitfather/28f580ef7df5aec0227a to your computer and use it in GitHub Desktop.
Save thegitfather/28f580ef7df5aec0227a to your computer and use it in GitHub Desktop.
wrap a new element around some RegExp
(function($) {
'use strict';
$.fn.wrapRegExp = function(options) {
// defaults
var settings = $.extend({
regExp: /([\s\S]*)/,
wrapper: '<div style="border:1px solid red;" />'
}, options);
return this.each(function(index, _this) {
var $this = $(_this);
var content = $this.html();
var $newContent;
if (settings.regExp.test(content)) {
content = content.replace(settings.regExp, function(match) {
$newContent = $(settings.wrapper);
$newContent.append(match);
// return it as string
return $newContent.prop('outerHTML');
});
$this[0].innerHTML = content;
return $this;
}
});
};
})(jQuery);
$(function() {
'use strict';
$('h1').wrapRegExp({
regExp: /(\w)+/g,
wrapper: '<span style="border:1px solid red;"/>'
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment