SO - Tag Replacement
Answer for http://stackoverflow.com/questions/8378575/get-string-between-two-strings-using-jquery .
by yusafkhaliq
HTML
<div class="comment-body">
[img]http://topnews.net.nz/images/YouTube-3.jpg[/img]
some text here
[youtube]http://www.youtube.com/watch?v=T1hf4B5pyjQ&feature=grec_index[/youtube]
</div>
<div class="comment-body">
[img]http://blog.brightcove.com/sites/all/uploads/FACEBOOK%20ICON.png[/img] text
</div>
<div class="comment-body">
[youtube]http://www.youtube.com/watch?v=T1hf4B5pyjQ&feature=grec_index[/youtube]
</div>
<div class="comment-body">
nothing to replace here
</div>
CSS
div {
border: 1px solid black;
margin-bottom: 10px;
}
JavaScript
var youtubeTag = /\[youtube\]https?:\/\/(?:www\.)?youtu(?:be\.com|\.be)\/(?:watch\?v=|v\/)?([A-Za-z0-9_\-]+)([a-zA-Z&=;_+0-9*#\-]*?)\[\/youtube\]/;
var youtubeHTML = '<div data-address="$1" class="youtube" style="background: url(http://i4.ytimg.com/vi/$1/hqdefault.jpg)"><span>CLICK HERE</span></div>';
var youtubeIFRAME = '<span class="close">CLOSE</span><iframe data-address="$1" class="youtube" src="http://www.youtube.com/embed/$1?rel=0" frameborder="0" allowfullscreen></iframe>';
$(".comment").each(function(){
var $this = $(this);
$this.html($this.html().replace(youtubeTag, youtubeHTML));
});
$(".comment").delegate("div.youtube", "click", function(){
var $this = $(this);
$this.replaceWith(youtubeIFRAME.replace(/\$1/g, $this.attr("data-address")));
});
$(".comment").delegate("span.close", "click", function() {
var $next= $(this).next();
$next.replaceWith(youtubeHTML.replace(/\$1/g, $next.attr("data-address")));
$(this).remove();
});
function replaceText(inputText, tagName, tagReplace) {
var regExp = new RegExp('\\[' + tagName+ '\\]([^\\[]*)\\[\/' + tagName + '\\]', 'g');
return inputText.replace(regExp, tagReplace);
}
$('.comment-body').each(function() {
var $this = $(this);
var replacedText = replaceText($this.text(), 'img', '<img src="$1" \/>');
$this.html(replacedText);
});