任务很简单。我写了一个函数,期望从object()的标识符和数组中替换字符串。
var replacer = function(original, replacement) {
console.log(replacement)
_.each(replacement, (value, key) => {
original = original.replace('${' + key+'}', value)
});
return original;
}
console.clear();
var asString = "This is my email ${email} & ${mobile}";
var replacement = {"email":"abcd@yahoo.co.in", "mobile":"999999999"}
asString = replacer(asString, replacement);
console.log(asString) // Here i am getting it properly replaced
var replacement ={"email":"xyz@yahoo.co.in", "mobile":"0000000"}
asString2 = replacer(asString, replacement);
console.log(asString2) // Here i am still getting old value not new value
如果你检查更新一个, http://jsfiddle.net/1gc9xka8/1
我甚至改变了变量,但仍然得到旧值。
请告知这里有什么问题。
答案 0 :(得分:1)
您正在传递替换的字符串而不是原始字符串
var replacer = function(original, replacement) {
console.log(replacement)
_.each(replacement, (value, key) => {
original = original.replace('${' + key + '}', value)
});
return original;
}
console.clear();
var asString = "This is my email ${email} & ${mobile}";
var replacement1 = {
"email": "abcd@yahoo.co.in",
"mobile": "999999999"
};
var asStringReplacement1 = replacer(asString, replacement1);
console.log(asStringReplacement1);
var replacement2 = {
"email": "xyz@yahoo.co.in",
"mobile": "0000000"
};
var asStringReplacement2 = replacer(asString, replacement2);
console.log(asStringReplacement2);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;