0

I have the following string and array:

var message = 'This is a @[20] very fun, @[75] evening.';
var array_values = {"20": "really", "112": "extreme", "75": "happy"};

How do I replace the @[number] occurrences with the corresponding array values, to get this:

message = 'This is a really very fun, happy evening.';

Thanks!

2
  • 3
    array_values is not an array.... Commented Oct 15, 2014 at 16:37
  • Yeah - array_values is an object. If you want an array, run Object.keys(array_values) to get an array containing the keys of that object. Commented Oct 15, 2014 at 17:17

3 Answers 3

2

One way:

var parsed = message.replace(/@\[(\d+)\]/g, function(m, v) {
    return array_values[v] || m;
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this using replace method:

var message = 'This is a @[20] very fun, @[75] evening.';
var array_values = {"20": "really", "112": "extreme", "75": "happy"};

for( var key in array_values ) {
  if( array_values.hasOwnProperty( key ) ) {
    message = message.replace( '@[' + key + ']', array_values[ key ] );
  }
}

console.log( message );

Comments

1

A possible way

for (var key in array_values) {
   message = message.replace('@[' + key + ']', array_values[key]);
}

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.