[英]Access object property name with for loop
I'm working on Emoji system based on JavaScript & Github Emoji icons , I use a function to trigger typing event, that's my code 我正在基于JavaScript和Github Emoji图标的Emoji系统上工作,我使用一个函数来触发输入事件,这就是我的代码
function myFunction() {
var y = document.getElementById("myInput").value;
var x = y.replace(/plus/g,'<img width="25" src="https://assets-cdn.github.com/images/icons/emoji/unicode/1f44d.png?v7" />');
document.getElementById("demo").innerHTML = "You wrote: " + x;
}
it's working well , but it's not smart . 它运作良好,但并不聪明。
I tried using an Array with for loop to handle the Github Emoji API 我尝试使用带有for循环的数组来处理Github Emoji API
var data = {
star: "https://assets-cdn.github.com/images/icons/emoji/unicode/2b50.png?v7"
};
for (var i in data) {
console.log(data[i]);
}
the for loop access the object property but not display it's name , I need the property name for replacement , the final code I expect is : for循环访问对象属性,但不显示其名称,我需要替换属性名称,我期望的最终代码是:
for (vari in data) {
var x = string.replace(/${property_name}/g, data[i]);
}
Try this: 尝试这个:
for (var key in data) {
if (data.hasOwnProperty(key)) {
var x = string.replace(new RegExp(key, "g"), data[key]);
}
}
When you use a for(var i in data)
loop i
is the object property not data[i]
当您使用
for(var i in data)
循环时, i
是对象属性而不是data[i]
Also, if you want to construct a regex pattern from a string you'll have to create a RegExp
object. 另外,如果要从字符串构造正则表达式模式,则必须创建一个
RegExp
对象。
For completeness, a better way might be to avoid the loop and make use of .replace
s ability to take a callback function: 为了完整起见,更好的方法可能是避免循环,并利用
.replace
的功能接受回调函数:
var data = {
star: "https://assets-cdn.github.com/images/icons/emoji/unicode/2b50.png?v7"
};
var pattern = new RegExp(Object.keys(data).join('|'), 'g');
var x = string.replace(pattern, function(match) { return data[match]; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.