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