BenM
BenM

Reputation: 53246

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 RegExp(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!

Upvotes: 1

Views: 313

Answers (3)

katspaugh
katspaugh

Reputation: 17919

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

Here's a demo.

Upvotes: 3

Dan
Dan

Reputation: 2038

I always use the following site to build Regex:

http://gskinner.com/RegExr/

Upvotes: 1

Surreal Dreams
Surreal Dreams

Reputation: 26380

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.

Upvotes: 1

Related Questions