1

I'm trying to replace strings with variables in the same way that Python string formatting works.

The string will be in a similar format to:

string = 'Replace $name$ as well as $age$ and $country$';

And I'd like to have a regex operation that will return and array:

['name', 'age', 'country'] or ['$name$', '$age$', '$country$']

So that I can map it to object keys:

{
 name    : 'Bob',
 age     :  50,
 country : 'US'
}

I've seen solutions using string concatenation but I need a solution using regex because I have to rely on strings containing these variables.

2
  • Should be simple enough. What have you tried so far? What is acceptable in one of your token names? Commented May 30, 2014 at 17:20
  • Anything really, as long as it isn't expected as actual content, so a single character would do as well as a combination. Commented May 30, 2014 at 20:11

1 Answer 1

3

You can do this:

var string = 'Replace $name$ as well as $age$ and $country$';
var arr = [];
string.replace(/\$(.+?)\$/g, function(m,g1){ arr.push(g1); return m; });
console.log(arr); // desired output
Sign up to request clarification or add additional context in comments.

5 Comments

That .+ should be .+? to make it not greedy.
@MattBurland, yeah I knew! Done
@Matt or you could use [^$]+
@TomFenech: Personally I prefer the non-greedy ?, but what you suggest would work as well. Really don't know if there's an actual benefit to one versus the other.
It would be nice if this solution allowed for an escape character so you could do something like `var string = 'Price: \$$price$'.

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.