如何在javascript或jQuery中将字符串中的出现替换为数组值
How to replace occurrences in string with array values in javascript or jQuery?
我有以下字符串和数组:
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]);
}
相关文章:
- 如何检查和替换数组中的值
- JavaScript:替换数组中的字符串
- 用对象属性替换数组元素
- 替换数组中已更改的元素
- 在javascript中使用regex和replace()替换数组元素
- innerhtml.replace没有替换数组javascript中的所有单词
- 替换数组中的一个字符串
- Jquery 字符串替换,只替换数组的开头
- JS:边缘情况问题 - 替换数组中的变量
- javascript 替换数组会导致更改整个列
- 元素不在数组javascript&替换数组
- 在JavaScript中全局替换数组模式中的字符串
- Javascript:用一个新值替换数组中的所有内容
- 如何替换数组
- 如何用另一个数组的元素替换数组中的元素
- Javascript:用另一组项替换数组中的项
- 在Javascript中,用另一个数组替换数组的部分的最快方法是什么?
- 使用javascript替换数组中的连续整数
- 字符串替换数组映射
- 在数组中搜索字符串/值,替换数组中的字符串/值