[英]closing a tag with javascript
我正在嘗試用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;
}
這段代碼在語法上是正確的-初始化temp_index
和text
並省略循環外的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.