在实际开发中,经常会遇到替换字符串的情况,但是大多数情况都是用replace替换一种字符串,本文介绍了如何使用replace替换多种指定的字符串,同时支持可拓展增加字符串关键字。   

         let content = `<div >

             </div>`;
let article
= content.replace(/(\<img|\<p|\<article|\<\/article|\<header|\<\/header)/gi, function ($0, $1) { return { "<img": '<img style="width:100%;height:auto;display:block;" ', "<p": '<p style="text-indent: 24px;" ', "<article":"<div", "</article": "</div", "<header": "<div", "</header": "</div" }[$1]; }); console.log(article)
replace里的g表示全局替换,而每个关键词前面的\则为转义字符,在针对html类的标签替换的时候,是必不可少的。


相关文章:

  • 2021-11-13
  • 2021-09-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-07
  • 2021-11-06
  • 2022-12-23
猜你喜欢
  • 2022-01-05
  • 2021-11-06
  • 2021-11-06
  • 2021-07-05
  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
相关资源
相似解决方案