转换 HTML 字符实体
请将字符串中的 & 、< 、> 、" (双引号)和 ' (单引号)转换为相应的 HTML 字符实体。
代码示例:
方法一:
function convertHTML(str) {
if(str.includes("&")){
str = str.replace(/&/g,'&');
}
if(str.includes("<")){
str = str.replace(/\</g,'<');
}
if(str.includes(">")){
str = str.replace(/\>/g,'>');
}
if(str.includes("'")){
str = str.replace(/\'/g,''');
}
if(str.includes('"')){
str = str.replace(/\"/g,'"');
}
console.log(str)
return str;
}
convertHTML("Dolce &<><&' Gabbana");
方法二:
function convertHTML(str) {
function repEnt(ent){
switch(ent){
case "&":
return "&";
case "<":
return "<";
case ">":
return ">";
case '"':
return '"';
case "'":
return "'";
}
}
str = str.replace( /[&<>"']/g, repEnt );
return str;
}
convertHTML("Dolce & Gabbana");
方法三:
function convertHTML(str) {
var temp = str.split("");
for (var i = 0; i < temp.length; i++) {
switch (temp[i]) {
case "<":
temp[i] = "<";
break;
case "&":
temp[i] = "&";
break;
case ">":
temp[i] = ">";
break;
case '"':
temp[i] = """;
break;
case "'":
temp[i] = "'";
break;
}
}
temp = temp.join("");
return temp;
}
convertHTML("Dolce & Gabbana");
方法四:
function convertHTML(str) {
var characters = [/&/g, /</g, />/g, /\"/g, /\'/g];
var entities = ["&", "<", ">", """, "'"];
for(var i = 0; i < characters.length; i++) {
str = str.replace(characters[i], entities[i]);
}
return str;
}
convertHTML("Dolce & Gabbana");
|