Find special markers in sequence and do something

2019-08-01 04:06发布

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 classes accordingly... while also removing the markers that once existed.

I found this Find Text Between 2 Quotes with jQuery but it gives little help as i could only make it work as it was.

This explains a little further: http://jsfiddle.net/ALfsT/3/

I have no idea where to go with this.

2条回答
成全新的幸福
2楼-- · 2019-08-01 04:49

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

查看更多
3楼-- · 2019-08-01 04:50

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);
查看更多
登录 后发表回答