W3Cschool中级脚本算法(11.html符号转实体算法挑战)

html符号转实体算法挑战


问题:

将字符串中的字符 &<>" (双引号), 以及 ' (单引号)转换为它们对应的 HTML 实体。


要求:

convert("Dolce & Gabbana") 应该返回 Dolce &​amp; Gabbana

convert("Hamburgers < Pizza < Tacos") 应该返回 Hamburgers &​lt; Pizza &​lt; Tacos

convert("Sixty > twelve") 应该返回 Sixty &​gt; twelve

convert('Stuff in "quotation marks"') 应该返回 Stuff in &​quot;quotation marks&​quot;

convert("Shindler's List") 应该返回 Shindler&​apos;s List

convert("<>") 应该返回 &​lt;&​gt;

convert("abc") 应该返回 abc


问题答案:

// &colon;&rpar;
  var entityMap = {
    '&' : '&amp;',
    '<' : '&lt;',
    '>' : '&gt;',
    '"' : '&quot;',
    "'" : '&apos;'
  };

  //新建一个以对象key为基础的正则匹配项,这样再增加更多的实体也比较好拓展了
  var regexp = new RegExp ('['+Object.keys(entityMap).join('')+']','g');

  return str.replace(regexp,function(matched){
    return entityMap[matched];
  });  

题目链接:

https://www.w3cschool.cn/codecamp/convert-html-entities.html

猜你喜欢

转载自blog.csdn.net/qq_42044073/article/details/82704356