1

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!

3 Answers 3

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

Here's a demo.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly my thoughts. Faster for about a minute :)
1

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.

Comments

1

I always use the following site to build Regex:

http://gskinner.com/RegExr/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.