简体   繁体   English

在JavaScript中的字符之间替换多个字符串

[英]Replace multiple strings between characters in JavaScript

I'm trying to replace strings with variables in the same way that Python string formatting works. 我正在尝试使用与Python字符串格式化相同的方式替换字符串。

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. 我已经看到使用字符串连接的解决方案,但我需要使用正则表达式的解决方案,因为我必须依赖包含这些变量的字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM