开发者

RegEx Replacement in JavaScript

I have a piece of code which replaces tokens in a string. I have the replacement values stored in an array.

Essentially, I would like to analyse the string and replace it by array key. For example, I want to replace any instance of [my_forename] with replacements['my_forname']. The keys in the array are identical to whatever is between the squared brackets in the string.

A more comprehensive view:

replacements['my_forename'] = 'Ben';
replacements['my_surname']  = 'Major';
replacements['my_verbose_name'] = 'Ben Major';

// The following is the input string:
// 'My name is [my_forename] [my_surname], or [my_verbose_name].';
// And it should output:
// 'My name is Ben Major, or Ben Major.';

If anyone can offer a RegEx that will handle the replacement, I would be grateful. It is possible that there will be more than one instance of the same token, but I have handled that using the following replaceAll function:

String.prototype.replaceAll = function(needle, replacement)
{
    return this.replace(new 开发者_如何学GoRegExp(needle, 'g'), replacement);
}

This causes a max stack limit though, because creating a RegExp object from anything containing [] causes issues.

Any help would be gratefully received!


function tmpl(s, o) {
    return s.replace(/\[(.+?)\]/g, function (_, k) { return o[k] })
}

Here's a demo.


Why not use sprintf() or vsprintf()? Check this page for reference: http://www.diveintojavascript.com/projects/javascript-sprintf

Rather than replace tokens, you have placeholders in a string that are replaced automatically with values, or in the case of vsprintf(), values straight from an array.


I always use the following site to build Regex:

http://gskinner.com/RegExr/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜