Skip to content

Instantly share code, notes, and snippets.

Created March 10, 2017 15:59
Show Gist options
  • Save anonymous/ec138465bfaa7b117136060c51fca60d to your computer and use it in GitHub Desktop.
Save anonymous/ec138465bfaa7b117136060c51fca60d to your computer and use it in GitHub Desktop.
jQuery Find Replace Plugin
<section>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
<p>It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of <b>Lorem Ipsum</b>.</p>
<a href="https://en.wikipedia.org/wiki/Lorem_ipsum">Lorem Ipsum Wikipedia Link</a>
</section>
<section>
<p>This <span class="small-u">lorem ipsum</span> should not be hilighted.</p>
</section>
<ul>
<li>A Lorem Ipsum List</li>
<li>More Elements Here</li>
</ul>
<p class="notification"></p>
(function($) {
$.fn.findReplace = function(options) {
var settings = $.extend({
findText: null,
replaceText: "",
customClass: "",
completeCallback: null
}, options);
return this.each(function() {
var StringToFind = settings.findText;
var regExpression = new RegExp(StringToFind, "g");
var replacement = "<span class='" + settings.customClass + "'>" + settings.replaceText + "</span>";
$(this).html(
$(this).html().replace(regExpression, replacement)
);
if ($.isFunction(settings.completeCallback)) {
settings.completeCallback.call(this);
}
});
};
}(jQuery));
$("a").findReplace({
findText: "Lorem Ipsum",
replaceText: "I was replaced too!",
customClass: "match-link",
completeCallback: function() {
$('.notification').text('Executed the plugin on all links').fadeOut(5000);
}
});
$("section").findReplace({
findText: "Lorem Ipsum",
replaceText: "Ipsum Lorem",
customClass: "match-section"
});
$("ul").findReplace({
findText: "Lorem",
replaceText: "Replaced"
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
body {
font-family: 'Dosis';
font-size: 1.3em;
width: 600px;
text-align: justify;
line-height: 1.8em;
}
.match-section {
background: #9F6;
border-radius: 3px;
padding: 2px;
}
.match-link {
background: #F96;
border-radius: 3px;
padding: 2px;
}
.notification{
border-radius: 3px;
background: rgba(0,0,0,0.9);
color: #fff;
padding: 4px;
position: fixed;
bottom: 0;
}
<link href="https://fonts.googleapis.com/css?family=Dosis" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment