Skip to content Skip to sidebar Skip to footer

Find Special Markers In Sequence And Do Something To The Text In Between

I wanna do something that would work much like this shortcode in stackexchange. So basically I want to wrap text with distinct markers and .wrap() them in spans with specific class

Solution 1:

Thanks @Guffa for the help here

http://jsfiddle.net/mplungjan/AkCED/

var res = {
    boldIt:/\*\*(.*?)\*\*/g,
    underlineIt:/\_\_(.*?)\_\_/g
}
var txt = $( "#texts" ).html();
$.each(res, function(type, re) {
  txt = txt.replace( re, '<span class="'+type+'" >$1</span>' );
});
$( "#texts" ).html(txt);

update:

now we need to code stuff like this http://jsfiddle.net/mplungjan/bhTAM/

You changed to class=texts I changed it back to id=texts and it worked better

var res = {
    boldIt:{re:/\*\*(.*?)\*\*/g,tag:"span"},
    underlineIt:{re:/\_\_(.*?)\_\_/g,tag:"span"},
    italicIt:{re:/\/\/(.*?)\/\//g,tag:"span"},
    titleIt:{re:/\=\=(.*?)\=\=/g,tag:"h1"},
    linkIt:{re:/\#\#(.*?)\:(.*?)\#\#/g, tag:"a"},
    imageIt:{re:/\"\"(.*?)\:(.*?)\"\"/g, tag:"img"}
}
var s = $("#texts").html();    
$.each(res, function(type, obj) {
  if(s) s = s.replace(obj.re,'<'+obj.tag+' class="'+type+'" >$1</'+obj.tag+'>');
});
$("#texts").html(s);

Solution 2:

You need to escape the * characters : /\*\*(.*?)\*\*/

I also suggest that you use a callback function to wrap your text : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

Post a Comment for "Find Special Markers In Sequence And Do Something To The Text In Between"