Find special markers in sequence and do something to the text in between

非 Y 不嫁゛ 提交于 2020-01-05 12:28:53

问题


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.


回答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);



回答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



来源:https://stackoverflow.com/questions/6995554/find-special-markers-in-sequence-and-do-something-to-the-text-in-between

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!