用javascript关闭标签

时间:2013-04-01 07:24:04

标签: javascript html text-formatting

我正在尝试使用javascript关闭标记,但是当它写入文档时,正斜杠总是丢失。我已经尝试用反斜杠(“\ /”)来加强它,但它确实似乎有所帮助。我一直在页面源上看到<pre>。这是代码:

var temp_index = 0,
    line_count = 0;
while (temp_index < text.length) {
    if ((text.charAt(temp_index) == "\n") && (line != line_count)) {
        if (line_count < line) line_count++;
        if (line_count == line) {
            text = text.substring(0, temp_index) + "<pre id='line'>" + text.substring(temp_index);
            temp_index++;
            while ((text.charAt(temp_index) != "\n") && (temp_index < text.length)) temp_index++;
            text = text.substring(0, temp_index - 1) + "<\pre>" + text.substring(temp_index);
        }
    }
    temp_index++;
}
return text;

我期待得到:

Heres's the last line
<pre id='line'>Here's the current line</pre>
Here's the next line
Here's the final line

但我得到了:

Here's the last line
<pre id='line'>Here's the current line
Here's the next line
Here's the final line</pre>

我通过用标签替换行尾的\ n进行了快速修复。 即使它解决了这个问题,它也会导致键盘输入中的错误。这是更新的代码。

if (line_count == line) {
    text = text.substring(0, temp_index) + "<pre id=\"line\">" + text.substring(temp_index);
    temp_index++;
    while ((text.charAt(temp_index) != "\n") && (temp_index < text.length)) temp_index++;
    text = text.substring(0, temp_index - 1) + "</pre>" + text.substring(temp_index);
    break;
}

1 个答案:

答案 0 :(得分:1)

此代码在语法上是正确的 - 初始化temp_indextext并省略循环外的break

temp_index = 0;
text = "this is \n a test \n of some info";

text =  text.substring( 0, temp_index )
     + "<pre id=\"line\">"
     + text.substring( temp_index );

temp_index++;

while( ( text.charAt( temp_index ) != "\n" ) && ( temp_index < text.length ) ) temp_index++;

text = text.substring( 0, temp_index - 1 )
     + "</pre>"
     + text.substring( temp_index - 1 );

alert(text);

结果

<pre id="line">this is</pre> 
 a test 
 of some info

您也可以使用replace重写当前行并获得与上述相同的结果:

text = "this is \n a test \n of some info";
text = text.replace(/(.+?)\n/, "<pre id=\"line\">$1</pre>\n"); 

如果您知道当前行,并希望将其添加到<pre id=\"line\">前面并附加</pre,我会使用split()join()

// update line 2
line = 2;

// sample text
text = "this is\n"+
       "a test\n"+
       "of some info";

// split to an array on newlines
vals = text.split("\n");

// replace the second line, which has an index of 1 (or line-1)
vals[line-1] = "<pre id=\"line\">" + vals[line-1] + "</pre>";

// join back to an array using newlines
text = vals.join("\n");

结果:

this is
<pre id="line">a test</pre>
of some info