搜索内容时替换搜索到的内容

  function replaceAll(str, searchStr, replacement) {
        
    if(!str) {

      return;

    }

    // searchStr 搜索的文字,用来截取特殊符号加 '\'

    // str 要替换的文字,用来最后替换

    // replacement 要替换成的文字

    // 如果高亮文本包含正则表达式转义符,需要在前面加 '\'

    // 正则表达式转义符

    let invalid = /[°"§%()\[\]{}=\\?´`'#<>|,;.:+_-]+/g;



    // 匹配特殊字符

    let repl = searchStr.match(invalid) || [];

    // 前面加 '\'

    // 如果文本中有两个以上特殊字符连接时,需要把他们切开成单个

    let replLast = []

    repl.length && repl.forEach((item) => {

      if (item.length > 1) {

        let replContent = item.split('')

        replLast.push(...replContent)

      } else {

        replLast.push(item)

      }

    })

    let newTextS = ''

    // 保存的新文本,特殊字符前加'\'

    let newSearchText = ''

    replLast.length && replLast.forEach((item) => {

      let n = searchStr.indexOf(item)

      if (n !== -1) {

        // 截取每个符合条件的字符串前面接'\'

        newTextS = searchStr.slice(0, n) + `\\${item}`

        // 获取截取后的文本

        searchStr = searchStr.slice(n + 1)

        newSearchText += newTextS

      }

    })

    // 截取完成后,剩余的也要加上

    newSearchText += searchStr

    let regExp = new RegExp(newSearchText, 'g')

    let newText = str.toString().replace(regExp, `${replacement}`)

    return newText

  }

// 例如
replaceAll('我是(祖国的花朵(1)),我是(祖国的花朵(1))', '我是(祖国的花朵(1))', '<em>我是(祖国的花朵(1))</em>')
// <em>我是(祖国的花朵(1))</em>,<em>我是(祖国的花朵(1))</em>"

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值