[英]replace string value with variable
I have an array of strings, within each string I want to call a variable 我有一个字符串数组,在每个字符串中我都想调用一个变量
Strings = ["$username thanks for visiting","Thanks $username, but I don't understand the command $userProvidedCommand"]
now I know I can use string replace 现在我知道我可以使用字符串替换
msg.replace('$username', userame)
however I don't want to write a string replace for every possibility. 但是我不想为所有可能的情况写一个字符串替换。
what would be ideal , I think. 我认为理想的是什么。 would be to have have some sort of pattern replacement where it looks for the $ and breaks the string up and concatenates it back together with the variable.
将进行某种形式的替换,在其中寻找$并将字符串分解并将其与变量连接在一起。
Is there a way to do that, or maybe there is a better solution ? 有没有办法做到这一点,或者有更好的解决方案?
thanks 谢谢
You can do it with regular expressions: 您可以使用正则表达式:
var data = {
username: 'peterpan',
userProvidedCommand: 'mycommand'
}
var format = function(data, str) {
return str.replace(/\$(\w+)/g, function(_, m) {
return data[m] || ''
})
}
var result = strings.map(format.bind(null, data))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.