开发者

Is there something like PHP's preg_replace_callback() in javascript?

开发者 https://www.devze.com 2023-01-02 18:50 出处:网络
What I want to do is str.replace(pattern, callback), not simply str.replace(pa开发者_如何学运维ttern, replace_pattern),

What I want to do is str.replace(pattern, callback),

not simply str.replace(pa开发者_如何学运维ttern, replace_pattern),

is it possible to do it in javascript?


Why, yes, you can do exactly that: str.replace(pattern, function () { ... }).

Here's some documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_the_replacement


Yes

var s2 = s1.replace(/regex/, function(whole, part1, part2, ...) { ... })

The function is passed the whole matched string as the first argument. If there are any capturing groups, those are passed as subsequent arguments.


The general case have no solution with s1.replace(/regex/, function(whole, part1, part2, ...partN) { ... }), where you need to know all parts and it is not valid g option;

arbitrary number of itens

The example of RegExp('\{([^\}]*)\}', 'g') can be solved by a loop... Supposing the URI-template problem, replacing each placeholder by global getData dictionary.

const tpl = 'myEtc/{aa}/etc1/{bb}/etc2'
const getData = {"aa":"expandAA","bb":"expandBB"}

function expandTpl(getData,s0){  // s0 is the link_template_input
  const r = RegExp('\{([^\}]*)\}', 'g');
  let s = '';
  let idx=0
  for (let a; (a=r.exec(s0)) !== null;) {
    s   += ( s0.substring(idx, r.lastIndex-a[0].length) + getData[a[1]] )
    idx = r.lastIndex
  }
  if ( idx<s0.length ) s += s0.substring(idx,s0.length)
  return s
}

console.log( tpl )
console.log( expandTpl(getData,tpl) )

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号