0

I want to replace something like this with jquery

['{star}'],['{heart}'],['{call}']

Whenever in BODY we got {star} , replace that with

<i class="fa fa-star"></i>

Or for {hear}{call}, etc.

How can i do this?

each element , {star} => fa fa-star, {heart}=> fa fa-heart

[EDIT SOLVED]

var str = "{heart}{star}"
var updated = str.replace(/\{([^}]+)}/g, '<i class="fa fa-$1"></i>');
document.body.innerHTML = document.body.innerHTML.replace(/\{([^}]+)}/g, '<i class="fa fa-$1"></i>');
Sara
  • 17
  • 4
  • Okay, what does your JQuery look like so far? I wont write the code for you, but you need to find the item you want, then replace it with the item in your array. – TGarrett Apr 14 '17 at 19:49
  • Might want to post a valid array – epascarello Apr 14 '17 at 19:49
  • $('body :not(script)').contents().filter(function() { return this.nodeType === 3; }).replaceWith(function() { var finds = ['{star}','{heart}']; var finds_to = ['StarS','HeartS']; return this.nodeValue.replace(finds[i],finds_to[i]); }); – Sara Apr 14 '17 at 19:50
  • I suppose you could parse the HTML and regex replace? – mhodges Apr 14 '17 at 19:50
  • 1
    As a nudge in the right direction: `document.body.innerHTML = document.body.innerHTML.replace(/{star}/g, '');` – Tyler Roper Apr 14 '17 at 19:50
  • @Santi it's work but how can i use with array ? – Sara Apr 14 '17 at 19:51
  • each element , {star} => , {heart}=> – Sara Apr 14 '17 at 19:53

1 Answers1

0

Simple regular expression to match anything between {}

var str = "I {heart} to eat an {apple}"
var updated = str.replace(/\{([^}]+)}/g, '<i class="fa fa-$1"></i>');
console.log(updated);

You could also replace it with ors with known strings.

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • thanks,it's true , but how this can find {heart} and {apple} in body content ? :( – Sara Apr 14 '17 at 20:01
  • replace the innerHTML? – epascarello Apr 14 '17 at 20:02
  • yeap replace to all of HTML content – Sara Apr 14 '17 at 20:02
  • http://stackoverflow.com/questions/15553280/replace-a-textnode-with-html-text-in-javascript – epascarello Apr 14 '17 at 20:03
  • this will replace html content to heart and apple , but don't replace just {heart} and {apple} ! – Sara Apr 14 '17 at 20:05
  • What is the actual HTML structure with the text.... If you gave the world thing, you can have a real answer.... – epascarello Apr 14 '17 at 20:07
  • sorry i'm new bie , sorry for my distrub :( – Sara Apr 14 '17 at 20:08
  • my question : in body we have {heart} , with jquery find {heart} and replace that to font awsome heart – Sara Apr 14 '17 at 20:09
  • I was working on a solution, during which @epascarello posted this great regex answer. I figured I shouldn't scrap everything I did, and instead incorporated his answer in mine. To avoid rewriting the entire body, you could do something like this: https://jsfiddle.net/mc9xnn8c/ (an Inspect Element will reveal that the proper font awesome tags are in the markup) – Tyler Roper Apr 14 '17 at 20:20