如何在javascript或jQuery中将字符串中的出现替换为数组值

How to replace occurrences in string with array values in javascript or jQuery?

本文关键字:替换 数组 javascript jQuery 字符串      更新时间:2023-09-26

我有以下字符串和数组:

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

如何用相应的数组值替换@[number]的出现,以获得以下内容:

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

谢谢!

单向:

var parsed = message.replace(/@'[('d+)']/g, function(m, v) {
    return array_values[v] || m;
});

您可以使用replace方法:

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 );

的一种可能方式

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