问题描述
(Q)如何将成千上万的{{1}}(不是 carriage returns
)从一个new lines
复制到另一个?
显然,textarea
是唯一无法正确复制的字符。
我想避免替换。
carriage return
自动转换为Carriage returns (code 13)
。"\n"
返回"\n".charCodeAt(0);
。
我需要它来返回它的原始值10
。
(Q)是否可以将所有已转换为13
的{{1}}转换回carriage returns
,而不转换未从{{ 1}}?
(A)是的。但是,将new lines
放在carriage returns
中时,您必须为new lines
使用carriage return
。然后,在获取substitute
中的carriage returns
时,将每个value
转换回textarea
。
解决方法
您不能将\r
复制到文本区域(至少在Firefox中经过测试),因为跨平台浏览器将回车符视为在某些操作系统下用作换行符,并替换掉带有换行符'\ n',因此在JavaSdcript中将其视为换行符。
类似地,如果将MSDOS新行对CRLF('\ r \ n`)放入文本区域,浏览器会将对转换为单个换行符。
,使用此脚本对我有用。
class HTMLTextCompatibilizer
{
carriageReturn = String.fromCharCode(13);
charCodeLimit = 65536;
substitute;
//find shortest substitute for particular string.
setSubstitute(string)
{
let substituteLength = 1;
let foundSubstitute = false;
while(!foundSubstitute)
{
for(let x = 0; x < this.charCodeLimit; x++)
{
this.substitute = String.fromCharCode(x).repeat(substituteLength);
if( !string.includes(this.substitute) &&
!this.substitute.includes(this.carriageReturn))
{foundSubstitute = true;}
}
substituteLength++;
}
return this.substitute;
}
//convert string with carriage returns to string with substitutes.
//use this every time you put a string from javascript into html.
toHTML(string)
{
let htmlString = "";
this.setSubstitute(string);
for(let x = 0; x < string.length; x++)
{
if(string[x] == this.carriageReturn)
{htmlString += this.substitute}
else
{htmlString += string[x]}
}
return htmlString;
}
//convert string with substitutes (back) to string with carriage returns.
//use this every time you load a string from html into javascript (after using toHTML()).
fromHTML(htmlString)
{
let string = "";
let substringEnd = this.substitute.length;
for(let x = 0; x < htmlString.length; x++)
{
if(htmlString.substring(x,substringEnd) == this.substitute)
{string += this.carriageReturn;}
else
{string += htmlString[x];}
substringEnd++;
}
return string;
}
}