System.Web.HttpUtility.HtmlAttributeEncode()
的实现
private static void HtmlAttributeEncodeInternal(string value, HttpWriter writer)
{
int index = HttpEncoder.IndexOfHtmlAttributeEncodingChars(value, 0);
if (index == -1)
{
writer.Write(value);
}
else
{
int length = value.Length;
int num = 0;
do
{
if (index > num)
writer.WriteString(value, num, index - num);
switch (value[index])
{
case '"':
writer.Write(""");
break;
case '&':
writer.Write("&");
break;
case '\'':
writer.Write("'");
break;
case '<':
writer.Write("<");
break;
}
num = index + 1;
if (num < length)
index = HttpEncoder.IndexOfHtmlAttributeEncodingChars(value, num);
else
goto label_6;
}
while (index != -1);
goto label_13;
label_6:
return;
label_13:
writer.WriteString(value, num, length - num);
}
}
使用 js 实现此功能:
function HtmlAttributeEncode(str) {
if (str) {
const len = str.length;
let i = 0;
let s = str[i];
let result = '';
do {
s = str[i];
if (s === '"') {
result += '"';
} else if (s === '&') {
result += '&';
} else if (s === '\\') {
result += ''';
} else if (s === '<') {
result += '<';
} else {
result += s;
}
} while (i++ < len - 1);
return result;
}
return str;
}
标签:index,num,C#,writer,value,js,Write,HttpUtility,str
From: https://www.cnblogs.com/fires/p/18396166