【问题标题】:regex to replace in javascript在javascript中替换的正则表达式
【发布时间】:2017-10-29 08:00:50
【问题描述】:

输入

'/api/v1' or '/_api/v1'

输出

'/'

我可以这样做

const output = input.replace('/api/v1', '/').replace('/_api/v1', '/');

但只是好奇我们如何利用 regex in replace 方法,并一次性完成?

【问题讨论】:

    标签: javascript regex string replace str-replace


    【解决方案1】:

    您可以使用简单的或条件|

    正则表达式:/api/v1|/_api/v1

    还有 javascript:

    const output = input.replace(/\/api\/v1|\/_api\/v1/g, '/');
    

    【讨论】:

      【解决方案2】:

      只需使用? 元字符添加下划线optional

      // using the constructor here to avoid all that forward-slash escaping
      const rx = new RegExp('/_?api/v1')
      const inputs = ['/api/v1', '/_api/v1']
      
      inputs.forEach(input => {
        console.info(input, ' becomes ', input.replace(rx, '/'))
      })

      【讨论】:

        【解决方案3】:

        试试这个模式\/_?api\/v\d+

        1. _? 是或条件有和没有_
        2. 并与d+ 一起使用,它将匹配v1&v2 末尾的数字

        Demo Regex and explanation

        var input1 = '/api/v1'
        var input2 = '/_api/v1'
        
        console.log(input1.replace(/\/_?api\/v\d+/g, '/'))
        console.log(input2.replace(/\/_?api\/v\d+/g, '/'))

        【讨论】:

          猜你喜欢
          • 2010-11-12
          • 2016-09-23
          • 1970-01-01
          • 1970-01-01
          • 2014-01-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多