js 中的replace()方法

  • Post author:
  • Post category:其他

基本用法例子

 const str = "我是谁的小可爱!" 
 //  /谁/正则表达式中间也能用“ | ”分隔 添加多个
     const ns = str.replace(/谁/,'ly').replace(/我/,'zq')
     console.log(ns); // zq是ly的小可爱

带正则exec的例子

const str = '<style>.first {color : yellow}</style> <script> for (let i = 0;i< 10;i++) {console.log(i)}</script>'
const regStyle = /<style>[\s\S]*<\/style>/;
const regScript = /<script>[\s\S]*<\/script>/;

const r1 = regStyle.exec(str)
console.log(r1);
//输出的结果为 一个数组 数组的第1个是正则匹配到的结果 我们对它进行字符替换
/*[
  '<style>.first {color : yellow}</style>',
  index: 0,
  input: '<style>.first {color : yellow}</style> <script> for (let i = 0;i< 10;i++) {console.log(i)}</script>',
  groups: undefined
]*/
const nC = r1[0].replace('<style>', '').replace('</style>', '')
console.log(nC); // 输出为 :.first {color : yellow}


const r2 = regScript.exec(str)
const nJ = r2[0].replace('<script>', '').replace('</script>', '')
console.log(nJ); //输出为: for (let i = 0;i< 10;i++) {console.log(i)}

参数带函数的例子

//这是一个字符替换函数 将特殊字符转换为html标签中表示特殊字符的符号  /g在正则中表示全局匹配 
function htmlEscape(htmlStr) {
    return htmlStr.replace(/<|>|"|&/g, match => {
        switch (match) {
          case '<':
            return '&lt;'
          case '>':
            return '&gt;'
          case '"':
            return '&quot;'
          case '&':
            return '&amp;'
        }
      })
  }
  const str = htmlEscape('<h1 >测试 <p>hello</p></h1>')
  console.log(str);// 输出为:&lt;h1 &gt;测试 &lt;p&gt;hello&lt;/p&gt;&lt;/h1&gt;

版权声明:本文为qq_46980517原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。