views:

49

answers:

1

i want to replace some selected character from my text-area with some string. To do this i wrote the following JavaScript code

            var old_tag = "[";
         var tag= " <xsl:value-of select = ";
      var endtag= " />";
var txt='';

if(document.selection)
{
 txt = document.selection.createRange().text
 document.selection.createRange().text = txt.replace(/\[/g, tag);
 document.selection.createRange().text = txt.replace(/\]/g, endtag);

}

But this code replacing one character at one line and another in another line. For two line of replacement code it is showing four lines.

Plz improve this code so that i can do my work in a single line.

Thanks

+1  A: 

You probably want to do something like:

txt = document.selection.createRange().text;
txt = txt.replace(/\[/g, tag).replace(/\]/g, endtag);
document.selection.createRange().text = txt;

replace does not have any side effects: it returns a new string, so you need to assign it to keep the change around.

jasonmp85