Jquery+(Regex?) Replace text with img from string -


i want replace text img using part of itself:

<li class='custom'>  <legend>images:</legend>  {[img.png][1desc][2desc]} {[img2.png][1desc2][2desc2} </li> 

i want appear this:

<li class='custom'>  <legend>images:</legend>  <img src="img.png" title="1desc - 2desc"/> <img src="img2.png" title="1desc2 - 2desc2"/> </li> 

current code using(doesn't work):

<script> function texttoimg(theimg) {   return theimg.replace(            /\{\s*[\s*(.*?)\s*]\s*[\s*(.*?)\s*]\s*[\s*(.*?)\s*]\s*\}/gi,            '<img src="$1" title="$2 - $3"/>'          ); }  jquery('li.custom').each(function() {      current = jquery(this);      img = texttoimg(current.html());      current.html(img);  }); </script> 

i haven't done jquery bit, since have been constructing solution on rather old ipod, regexp part trick.

first put little utility function rall(r,s) apply regexp method exec(s) multiple times on regular expression r. function return array of arrays, each 1 of structure [whole match,capture1,capture2,capture3,...].

the regular expression string put 3 subparts t (please note double \: 1 of them eaten @ string generation time) , turned regular expression new regexp(string, flags).

using javascript array methods map() , join() turned string again stored original string s (see console output).

var t,r,s='{[img.png][name1][desc1]} {[img2.png][name2][desc2]}';  function rall(r, s) { // utility: apply r.execs(s) multiple times  var a=[],t,g=r.global;  {t=r.exec(s);if (!t) break;      a.push(t);} while (g);  return a; }  t='\\s*\\[\\s*(.*?)\\s*\\]'; r=new regexp('\\{'+t+t+t+'\\s*\\}','g'); s=rall(r,s).map(function(f){  return '<img src="'+f[1]+'" title="'+f[2]+'">'+f[3]; }).join('<br>\n'); console.log(s); 

just noticed configured output little different yours. leave put right. ;-)

edit

having played around little utility function , getting work 1 thing ...

but - using regular expression above (here: written out directly)

r=\{\s*\[\s*(.*?)\s*\]\s*\[\s*(.*?)\s*\]\s*\[\s*(.*?)\s*\]\s*\}/g; 

you can whole thing 1 string.replace() call:

s.replace(r,'<img src="$1" title="$2 - $3">'); 

this produce

<img src="img.png" title="name1 - desc1"> <img src="img2.png" title="name2 - desc2"> 

Comments

Popular posts from this blog

php - Zend Framework / Skeleton-Application / Composer install issue -

c# - Better 64-bit byte array hash -

python - PyCharm Type error Message -