0

I'm working on Emoji system based on JavaScript & Github Emoji icons , I use a function to trigger typing event, that's my code

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

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 (vari in data) {
var x = string.replace(/${property_name}/g, data[i]);
} 
Saber Hosney
  • 112
  • 1
  • 12
  • 2
    Instead of logging `data[i]` - just log `i` - `i` is the property name. And you don't have an array, you have an object. – tymeJV Apr 18 '17 at 19:10

2 Answers2

2

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]

Also, if you want to construct a regex pattern from a string you'll have to create a RegExp object.

Titus
  • 22,031
  • 1
  • 23
  • 33
  • what I don't understand here , why I need the `hasOwnProperty` ? – Saber Hosney Apr 18 '17 at 19:15
  • that's working , but I can't approve answer yet , there's a problem : I can'r access data[key] inside HTML . Example : https://codepen.io/Pro-Fun/pen/MmaPaN?editors=1010 – Saber Hosney Apr 18 '17 at 19:24
1

For completeness, a better way might be to avoid the loop and make use of .replaces ability to take a callback function:

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]; });
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143