开发者

Replacement of text using JavaScript

开发者 https://www.devze.com 2023-01-01 17:52 出处:网络
i want to replace some selected char开发者_Go百科acter from my text-area with some string. To do this i wrote the following JavaScript code

i want to replace some selected char开发者_Go百科acter 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号