【发布时间】:2013-04-01 07:24:03
【问题描述】:
我正在尝试使用 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 = 0;并且您的break不在您的while循环内(您没有大括号)跨度> -
你的预期输出是什么?
-
temp_index 已初始化,我删除了中断。我更新了问题以显示我的预期输出
标签: javascript html text-formatting