Sara
Sara

Reputation: 17

Allow To Specific Text For Replace

I try to create something like this:

If in HTML, find {{heart}} text, then replace that with font awesome heart.

{{heart}} => fa fa-heart

In this code (below), you can use a CSS class.

Example: you can use something like this : {{heart red}}

But I don't like that!

I want to create something like rule, so that you can use just: {{heart}}, {{star}}, {{apple}}.

and if you try to use another that, it won't work.

Something like a 2d array:

{{heart}} => fa fa-heart,

{{star}} => fa fa-star,

etc.

I have this code:

	$(document).ready(function(){
	document.body.innerHTML = document.body.innerHTML.replace(/\{{([^}]+)}}/g, '<i class="fa fa-$1"></i>');
});

Upvotes: 0

Views: 47

Answers (1)

repzero
repzero

Reputation: 8402

A very easy method would be to use the browser itself to do all the parsing and matching.

  • create an element that will not be appended to the dom
  • check if the element has the class name, if not append it to the class name
  • finally return the outerhtml string of the element

    Snippet below

    function class_detector(classnames, html) {
      //chrome you need to place el in parent in order to set html
      var parent = document.createElement("div");
      var el = document.createElement("i");
      parent.appendChild(el);
      el.outerHTML = html;
      for (var x = 0; x < classnames.length; ++x) {
        if (!el.classList.contains("fa-" + classnames[x])) {
          el.classList.add("fa-" + classnames[x])
        }
      }
    
      return el.outerHTML;;;
    }
    
    var output = class_detector(["apple", "pear"], '<i class="fa another-class></i>')
    console.log(output);;

    Upvotes: 1

  • Related Questions