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
3 Answers
Reset to default 23Why, 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
版权声明:本文标题:regex - Is there something like PHP's preg_replace_callback() in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738347287a2078311.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论