I'm trying to close a tag with javascript but when it writes to the document the forward slash is always missing. I've tried preceding it with a back slash ( "\/" ) but it does seem to help. I keep seeing <pre> on the page source. Here's the code:

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;

I'm expecting to get:

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

But I'm getting:

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

I made a quick fix by replacing the \n at the end of the line with the tag. Even though it fixes this problem, it causes bugs in the keyboard input. Here's the updated code.

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;
}
有帮助吗?

解决方案

This code is syntactically correct - initializes temp_index and text and omits the break outside of a loop:

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);

Results in

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

You can also use replace to rewrite the current line and get the same result as above:

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

If you know the current line and want to prepend it with <pre id=\"line\"> and append it with </pre I would use split() and 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");

Result:

this is
<pre id="line">a test</pre>
of some info
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top