admin管理员组

文章数量:1186436

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

not simply str.replace(pattern, replace_pattern),

is it possible to do it in javascript?

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

not simply str.replace(pattern, replace_pattern),

is it possible to do it in javascript?

Share Improve this question asked Jun 4, 2010 at 3:15 wampwamp 5,94917 gold badges54 silver badges84 bronze badges 1
  • Here is an example: stackoverflow.com/questions/2966172/… – Amarghosh Commented Jun 4, 2010 at 3:55
Add a comment  | 

3 Answers 3

Reset to default 23

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) )

本文标签: regexIs there something like PHP39s pregreplacecallback() in javascriptStack Overflow