askquestionzero askquestionzero - 4 months ago 15
Javascript Question

Change tag name based on attribute using jquery and textarea

i am here again asking question

here is my text from my textarea

<Abstract>
<Heading>Abstract</Heading>
<Para TextBreak="No">Some paragraph <Emphasis Type="Italic">q</Emphasis> </Para>

</Abstract>


Possible output

<Abstract>
<Heading>Abstract</Heading>
<P>Some paragraph <i>q</i> </P>
</Abstract>


this is the reason of the output

the text are from text area.

i need to change the tag name based on its attribute

all Para tag must be changed to P tag

and all

Type="Italic" attribute must be change to <i> tag


i searched for a solution

but the solution i found are modifying the html. and not the content of the text area. thank you so much
this is the solution i found but i can't make it work to my problem

$(function(){
$('#switch').bind('click', function(){
$('p').replaceWith($('<div/>').html($('p').html()));
});
});


here is the sample of what i need. thank you

https://jsfiddle.net/bc6xequ7/

Answer

Please try doing it like below. This will not remove your attributes inside tag <para> and type="Italic". But it will definitely replace your tags as you want.

jQuery(document).ready(function(){
textval = $('textarea').val();
textnewval = textval.replace('Para TextBreak="No"', 'p').replace('/Para', '/p'); 
  
  if(textnewval.indexOf('Italic') >= 0) //If Italic
{
	EmphasisAttr = 'Italic';
  textnewval = textnewval.replace('Emphasis Type="'+EmphasisAttr+'"', 'i').replace('/Emphasis', '/i'); 
}
if(textnewval.indexOf('Bold') >= 0) //If Bold
{
	EmphasisAttr = 'Bold';
  textnewval = textnewval.replace('Emphasis Type="'+EmphasisAttr+'"', 'b').replace('/Emphasis', '/b'); 
}
if(textnewval.indexOf('Underline') >= 0) //If underline
{
	EmphasisAttr = 'Underline';
	textnewval = textnewval.replace('Emphasis Type="'+EmphasisAttr+'"', 'u').replace('/Emphasis', '/u'); 
}
 

  $('textarea').val(textnewval);
  alert($('textarea').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="20" >
  <Abstract>
    <Heading>Abstract</Heading>
    <Para TextBreak="No" >Some paragraph <Emphasis Type="Italic">q</Emphasis><Emphasis Type="Bold">Bold</Emphasis><Emphasis Type="Underline">Underline</Emphasis> </Para>

</Abstract>
</textarea>

Let me know if it is not what you expect.

Comments